创建线程的三种方式

/**
 * 创建线程的三种方式,很多的是视频和课本上只讲了两种创建线程的方式,其实最骚的那种没有讲到,那就看看三种方式都是怎样创建的
 */
1.继承Thread类
public class CreateThread {
    public static void main(String[] args){
        //1.创建线程
        MyThread thread = new MyThread();      //新建状态
        thread.start();                    //启动线程,就绪状态
        MyThread thread1 = new MyThread();      //新建状态
        thread1.start();                    //启动线程,就绪状态
    }

}
//线程类
class MyThread extends Thread{
    @Override
    public void run() {
        for (int i=0;i<5; i++){

            System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
2.实现runnable接口
public static void main(String[] args){
       //1.new 一个runnable实现类对象
       MyThread1 runnable = new MyThread1();
       //2.创建线程
       Thread thread1  =  new Thread(runnable,"thrad1");   //@param  thread1是线程名称
       thread1.start();
       Thread thread2  =  new Thread(runnable,"thrad2");   //@param  thread1是线程名称
       thread2.start();

    }
    //runnable实现类
    class MyThread1 implements  Runnable{

    @Override
    public void run() {
        for (int i=0;i<5; i++){

            System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


3.callable和FutureTask的配置使用,这是最厉害的一个,之前的两种线程无法带返回值,callable中的call()可以带Object类型的返回值


 public static void main(String[] args){
       //1.new Callable接口得实现对象
       MyThread3 callable = new MyThread3();
       //2.创建FuturTask对象
       FutureTask<Integer> ft = new FutureTask<>(callable);
       //3.创建线程
       Thread threa1 = new Thread(ft);
       threa1.start();
       try {
           int sum = ft.get();   //取线程的返回值
       } catch (InterruptedException e) {
           e.printStackTrace();
       } catch (ExecutionException e) {
           e.printStackTrace();
       }

   }
}

class MyThread3 implements Callable<Integer> {

    @Override
    public Integer call() {
        int count = 0;               //定义线程返回值

        for (int i=0;i<5; i++){

            System.out.println(Thread.currentThread().getName()+"--"+i);

            count++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return count;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值