星辰江河

多线程的三种创建方式

创建线程方式:

1.继承Thread类,重写run()方法,调用star()

public class TestThread1 extends Thread {

    @Override
    public void run() {
       //run方法线程体
        for (int i=0;i<=100;i++){
            System.out.println("我在看代码====>"+i);
        }
    }

    public static void main(String[] args) {
        // mian线程,主线程
        TestThread1 ts1=new TestThread1();
        // 启动线程
        ts1.start();
                
        for (int i=0;i<=100;i++){
            System.out.println("我在学习多线程====>"+i);
        }
    }
}

 

2.实现Runnable接口,重写run()方法,执行需要丢入runable接口实现类。调用star()

public class TestThread1 implements Runnable {

    @Override
    public void run() {
       //run方法线程体
        for (int i=0;i<=100;i++){
            System.out.println("我在看代码====>"+i);
        }
    }

    public static void main(String[] args) {
        // mian线程,主线程
        TestThread1 ts1=new TestThread1();
        Thread thrad=new Thread(ts1);
        // 启动线程
        thrad.start();

        for (int i=0;i<=100;i++){
            System.out.println("我在学习多线程====>"+i);
        }
    }
}

 

3.实现Callable接口(不常用),重写call方法,有返回值

// 实现Callable,返回Boolean
public class TestThread1 implements Callable<Boolean> {

    private String name;
    public TestThread1(String name){
        this.name=name;
    }

    @Override // 重写方法
    public Boolean call() {
        System.out.println(name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException ,InterruptedException{
         
        TestThread1 ts1=new TestThread1("张三");
        TestThread1 ts2=new TestThread1("李四");

        // 创建执行服务
        ExecutorService ser= Executors.newFixedThreadPool(2);
        // 提交执行
        Future<Boolean> r1= ser.submit(ts1);
        Future<Boolean> r2= ser.submit(ts2);
        // 读取结果
        boolean rs1=r1.get();
        boolean rs2=r2.get();
        // 关闭服务
        ser.shutdownNow();

    }
}

 好处:(1)可以定义返回值;

    (2)可以抛出异常;

 缺点:实现方法非常复杂

 

posted on 2021-09-07 15:04  星辰江河  阅读(92)  评论(0编辑  收藏  举报

导航