0
点赞
收藏
分享

微信扫一扫

线程创建的三种方式

一枚路过的程序猿 2022-03-30 阅读 150

一、.线程创建

线程创建的三种方式

1.继承Thread

// 创建⽅式 1:继承 Thread
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("你好,线程~");
   }
}
// 测试类
public class ThreadExample {
    public static void main(String[] args) {
        // 创建线程
        Thread thread = new MyThread();
        // 启动线程
        thread.start();
   }
}

2.实现Runnable

①匿名Runnable方式

Thread t2 = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Runnable方法~");
   }
});
// 启动线程
t2.start();

②匿名方式创建子对象

Thread t1 = new Thread() {
    @Override
    public void run() {
        System.out.println("线程变种");
   }
};
// 启动线程
t1.start();

使⽤ Lambda 匿名 Runnable ⽅式

Thread t3 = new Thread(() -> {
    System.out.println("我是变种 2~");
});
// 启动线程
t3.start();

3.带返回值的 Callable

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 线程创建示例 3
*/
public class CreateThreadExample3 {
    // 创建⽅式 3:实现 Callable 接⼝
    static class MyCallable implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int num = new Random().nextInt(10);
            System.out.println("⽣成随机数:" + num);
            return num;
       }
   }
    // 测试⽅法
    public static void main(String[] args) throws ExecutionException,
InterruptedException {
        // 创建 Callable ⼦对象
        MyCallable callable = new MyCallable();
        // 使⽤ FutureTask 配合 Callable ⼦对象得到执⾏结果
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        // 创建线程
        Thread thread = new Thread(futureTask);
        // 启动线程
        thread.start();
        // 得到线程执⾏的结果
        int result = futureTask.get();
        System.out.println("主线程中拿到⼦线程执⾏结果:" + result);
   }
}

 

举报

相关推荐

0 条评论