package com.zy.c_000_threadbasic;
import java.util.concurrent.*;
// 创建线程的五种方式,实际上是一种
public class To2_HowToCreateThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 方式一:继承Thread类,并复写run方法,创建该类对象,调用start方法开启线程。此方式没有返回值。
new MyThread().start();
// 方式二:实现Runnable接口,复写run方法,创建Thread类对象,将Runnable子类对象传递给Thread类对象。调用start方法开启线程。此方法2较之方法1好,将线程对象和线程任务对象分离开。降低了耦合性,利于维护。此方式没有返回值。
new Thread(new MyRun()).start();
// 方式三:使用Lambda表达式
new Thread(()->{
System.out.println("Hello Lambda");
}).start();
// 方式四:线程池 提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。
ExecutorService service = Executors.newCachedThreadPool();
service.execute(()->{
System.out.println("Hello ThreadPool");
});
service.shutdown();
// 方式五:带返回值的线程。实现Callable接口
FutureTask<String> task = new FutureTask<String>(new MyCall());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
// 可以跟线程池联合使用的
ExecutorService service01 = Executors.newCachedThreadPool();
Future<String> future = service01.submit(new MyCall());
// 这是一个阻塞类型的方法
String s = future.get();
System.out.println(s);
service.shutdown();
}
// 方式一:
static class MyThread extends Thread {
@Override
public void run(){
System.out.println("Hello MyThread!");
}
}
// 方式二:
static class MyRun implements Runnable {
@Override
public void run() {
System.out.println("Hello MyRun!");
}
}
// 方式五:
static class MyCall implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("Hello MyCall");
return "success";
}
}
}
创建线程的五种状态
猜你喜欢
转载自blog.csdn.net/m0_70299172/article/details/130775097
今日推荐
周排行