import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import static java.lang.Thread.sleep;
/**
* 创建线程方式
* 1. 继承Thread类
* 2. 实现Runnable接口,重写run()方法
* 3. 实现Callable接口,
* 4. 使用线程池
* <p>
* run()定义任务
* start() 启动线程 (线程启动必须调用start()方法,不然还会是main线程执行)
*/
public class Demo01 {
public static void main(String[] args) throws Exception {
// 1 继承Thread类
Thread athread = new AThread();
athread.start();
// 2. 实现Runnable 接口
Runnable bThread = new BThread();
new Thread(bThread).start();
//3.实现Callable接口,可以获取线程返回值
FutureTask futureTask = new FutureTask(new CThread());
Thread threadc = new Thread(futureTask);
threadc.start();
//获取Callable线程 call()方法返回值
//get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
Object o = futureTask.get();
System.out.println("Callable接口返回值 = " + o);
}
}
/**
* 继承Thread类,重写run()方法
*/
class AThread extends Thread {
@Override
public void run() {
//需要执行的任务
System.out.println("Thread :"+Thread.currentThread());
}
}
/**
* 实现Runable接口重写run()方法
*/
class BThread implements Runnable {
@Override
public void run() {
//需要执行的任务
System.out.println("Runnable :"+Thread.currentThread());
}
}
/**
* 实现Callable接口重写call()方法
*/
class CThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
//需要执行的任务
System.out.println("Callable :"+Thread.currentThread());
return 0;
}
}
// 线程池获取线程
ThreadPoolExecutor pool =
new ThreadPoolExecutor(5, 10, 1, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.AbortPolicy());
// 提交带返回值的任务
Future<?> future = pool.submit(() -> {
});
Object retObj = future.get();
// 提交不带返回值的任务
pool.execute(() -> {
});