【转载】线程创建的三种方式
参考
- https://www.bilibili.com/video/BV1V4411p7EF?p=9&spm_id_from=pageDriver
- https://blog.csdn.net/Hubz131/article/details/103096867
- https://blog.csdn.net/zhuchunyan_aijia/article/details/121756472
- https://blog.csdn.net/qq_40270751/article/details/78843226
介绍
- 继承 Thread 类,并重写 run 方法,没有返回值。
- 实现 Runnable 接口,并重写 run 方法(还是通过Thread实现的多线程),支持实现多个类,没有返回值。
- 实现 Callable 接口,并重写 call 方法,有返回值,可以通过线程池调用及 Thread 执行。
示例代码
- 继承 Thread
package thread;
/**
* 继承 Thread 类并重写run方法
* @Author 夏秋初
* @Date 2022/2/21 21:32
*/
public class TestThread extends Thread{
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
TestThread testThread0 = new TestThread();
testThread0.setName("0");
TestThread testThread1 = new TestThread();
testThread1.setName("1");
TestThread testThread2 = new TestThread();
testThread2.setName("2");
testThread0.start();
testThread1.start();
testThread2.start();
}
}
- 实现 Runnable
package thread;
/**
* @Author 夏秋初
* @Date 2022/2/21 21:38
*/
public class TestRunnable implements Runnable{
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread0 = new Thread(new TestRunnable(), "0");
Thread thread1 = new Thread(new TestRunnable(), "1");
Thread thread2 = new Thread(new TestRunnable(), "2");
thread0.start();
thread1.start();
thread2.start();
}
}
- 实现 Callable
package thread;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;
/**
* @Author 夏秋初
* @Date 2022/2/21 21:45
*/
public class TestCallable implements Callable<String> {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
public static void main(String[] args) throws InterruptedException,ExecutionException {
TestCallable testCallable = new TestCallable();
// 不使用线程池
FutureTask<String> futureTask = new FutureTask<String>(testCallable);
//
new Thread(futureTask, "不使用线程池获取线程执行结果").start();
//
System.out.println(futureTask.get());
//
System.out.println("======");
// 使用线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
//
Set<Future<String>> arrayList = new HashSet<>(10);
//
for (int i = 0; i < 10; i++) {
Future<String> future = executorService.submit(testCallable);
arrayList.add(future);
}
//
executorService.shutdown();
arrayList.forEach(item->{
try {
System.out.println(item.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/15920893.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/15920893.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。

浙公网安备 33010602011771号