2 创建线程的几种方式

创建线程的几种方式

方式1 重写Thread中的run方法

//方式一 重写Thread中的run方法
public class CreateThread1 {
   public static void main(String[] args) {
       //指定线程名称subThread0
       Thread t = new Thread("subThread0"){
           @Override
           public void run(){
               System.out.println("subThread0 running");
           }
       };

       //运行创建的线程subThread0
       t.start();
       System.out.println("main running");
   }
}

方式2 实现Runnable接口中的run方法

//方式2 实现Runnable接口中的run方法,配合Thread
public class CreateThread2 {
   public static void main(String[] args) {
		//任务对象
       Runnable runnable = new Runnable() {
           @Override
           public void run() {
               System.out.println("runnable running");
           }
       };
		//线程对象
       Thread t = new Thread(runnable);
       //运行创建的线程
       t.start();

       System.out.println("main running");
   }
}

//方式2 lambda简化实现
public class CreateThread3 {

   public static void main(String[] args) {
		//lambda简化
       Runnable runnable = () -> {
           System.out.println("subThread running");
       };

       Thread t = new Thread(runnable);
       t.start();

       System.out.println("主线程在运行");
   }
}

方式3 实现FutureTask接口中的call方法

//方式3 实现FutureTask接口中的call方法
public class CreateThread4 {
   public static void main(String[] args) throws ExecutionException, InterruptedException {

       //FutureTask实现了RunnableFuture接口,RunnableFuture接口中继承了Runnable, Future接口
       //泛型为call方法返回的类型
       FutureTask<Integer> task = new FutureTask(new Callable<Integer>() {
           @Override
           public Integer call() throws Exception {

               System.out.println("subTread running");
               //线程睡眠1s
               Thread.sleep(1000);
               return 1000;
           }
       });

       Thread t1 = new Thread(task, "t1");
       t1.start();
       //FutureTask的方式,可以得到call()方法的返回值,通过FutureTask中的get()方法得到
       //主线程会阻塞
       Integer res = task.get();
       System.out.println(res);

       System.out.println("main running");
   }
}

posted @ 2023-06-26 21:54  渺阴丶  阅读(7)  评论(0)    收藏  举报