java多线程

创建一个线程

Java 提供了三种创建线程的方法:

通过继承 Thread 类本身;

java 复制代码
public class MyThread extends Thread{
    // 重写run方法  里面放要执行的代码
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println("线程" + Thread.currentThread().getName() + "运行,i = " + i);
        }
    }
}
java 复制代码
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1=new MyThread();
        MyThread t2 = new MyThread();

        t1.setName("线程1");
    
        t2.setName("线程2");
    
        t1.start();
    
        t2.start();
    
    }

}

通过实现 Runnable 接口;

1.自定义一个类实现Runnable接口

2.重写run方法

3.创建自己的类对象

4.创建一个Thread类的对象,并开启线程

java 复制代码
public class MyRun implements Runnable{
    @Override
    public void run(){
        for (int i = 0; i < 100; i++){

            System.out.println("线程" + Thread.currentThread().getName() + "运行,i = " + i);
        }
    }

}
java 复制代码
public class ThreadDemo2 {
    public static void main(String[] args) {
        // 创建线程任务
        MyRun run=new MyRun();
        // 创建线程
        Thread t = new Thread(run);
        t.setName("线程1");
        t.start();

    }

}

通过 Callable 和 Future 创建线程。

可以获得多线程运行的结果

java 复制代码
import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call()throws Exception {
        //求1-100之间的和
        int sum=0;
        for(int i=1;i<=100;i++){
            sum+=i;
        }
        return sum;
    }
}
java 复制代码
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadDemo3  {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建MyCallable对象(表示多线程要执行的任务)
        MyCallable mc = new MyCallable();
        //创建一个FutureTask对象(作用管理多线程运行的结果)
        FutureTask<Integer> ft=new FutureTask(mc);
        //创建线程对象
        Thread t1=new Thread(ft);
        //启动线程
        t1.start();
        //获取线程运行结果
        Integer result=ft.get();
        System.out.println(result);
    
    }

}

守护线程

作用在于主线程结束后,自动结束

复制代码
t2.setDaemon(true);

出让线程

复制代码
Thread.yield();  
使得重新抢夺线程 ,让执行更均匀一些

插入线程

复制代码
t1.join();  将t1插入让此进程先执行
相关推荐
5:001 分钟前
云备份项目
linux·开发语言·c++
面朝大海,春不暖,花不开17 分钟前
自定义Spring Boot Starter的全面指南
java·spring boot·后端
得过且过的勇者y18 分钟前
Java安全点safepoint
java
笨笨马甲38 分钟前
Qt Quick模块功能及架构
开发语言·qt
夜晚回家1 小时前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS3141 小时前
C++动态规划-01背包
开发语言·c++·动态规划
斯普信云原生组1 小时前
Docker构建自定义的镜像
java·spring cloud·docker
前端页面仔1 小时前
易语言是什么?易语言能做什么?
开发语言·安全
wangjinjin1801 小时前
使用 IntelliJ IDEA 安装通义灵码(TONGYI Lingma)插件,进行后端 Java Spring Boot 项目的用户用例生成及常见问题处理
java·spring boot·intellij-idea
wtg44521 小时前
使用 Rest-Assured 和 TestNG 进行购物车功能的 API 自动化测试
java