创建线程的3种方式

转自https://blog.csdn.net/weixin_49920327/article/details/123561378

1. 继承Thread类

1)创建一个类,继承 Thread并重写 run 方法
2)创建对象 执行 start 方法

//创建线程方式一:继承Thread类,重写run()方法,调用start()开启线程
public class TestThread1 extends Thread{

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

    public static void main(String[] args) {
        //main()线程,主线程
        //创建一个对象
        TestThread1 testThread1 = new TestThread1();
        //调用start()方法
        testThread1.start();

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

2. 实现Runnable接口

1)创建一个类 实现Runnable接口并实现 run 方法
2)创建一个 该类 对象
3)创建一个 Thread 对象,构造方法入参为 该类 对象
4)Thread 对象 执行start方法

//创建线程方式2:实现runnable接口,重写run方法,执行线程丢入runnable接口实现类,调用start()方法
public class TestThread3 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("线程" + i);
        }
    }

    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();
        //创建线程对象,通过线程对象来开启我们的线程,代理
//        Thread thread = new Thread(testThread3);
//        thread.start();
        new Thread(testThread3).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("学习" +i);
        }
    }
}

3. 实现Callable接口(了解)

1)创建一个类实现 Callable 接口 ,重写 call 方法
2) 创建目标对象
3) 创建一个执行服务
4)提交执行
5)获取返回结果
6)关闭执行服务

//实现一个类,重写call()方法,
public class TestCallable implements Callable<Boolean> {
    @Override
    public Boolean call() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + "在上班-----" + i);
        }
        return Boolean.TRUE;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable();
        TestCallable t2 = new TestCallable();
        TestCallable t3 = new TestCallable();
        
        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        
        //提交执行
        Future<Boolean> result1 = executorService.submit(t1);
        Future<Boolean> result2 = executorService.submit(t2);
        Future<Boolean> result3 = executorService.submit(t3);
        
        //获取结果
        Boolean r1 = result1.get();
        Boolean r2 = result2.get();
        Boolean r3 = result3.get();
        
        //关闭服务
        executorService.shutdownNow();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值