public class MyThread {
/**
* 第一种
*/
static class TestThread extends Thread{
@Override
public void run(){
System.out.println("test thread");
}
}
/**
* 第二种
*/
static class TestRunnable implements Runnable{
@Override
public void run() {
System.out.println("test runnable");
}
}
static class TestCall implements Callable<String> {
@Override
public String call() throws Exception {
System.err.println("call方法执行");
Thread.sleep(3000);
return "success!!!";
}
}
public static void main(String[] args) throws Exception{
/**
* 面试题:实现Runnable接口和继承Thread类两种实现线程的方式那种好呢?
* 回答:java是单继承多实现的,所以实现runnable接口更好一点
*/
new TestThread().start();
new Thread(new TestRunnable()).start();
/**
* 第三种
*/
new Thread(() -> {
System.out.println("lambada表达是实现线程");
}).start();
/**
* 第四种,线程池实现线程
*/
ExecutorService service = Executors.newCachedThreadPool();
service.execute(()->{
System.out.println("线程池方式创建线程");
});
/**
* 第五种,带返回值的线程,f.get()方法是阻塞的
*/
Future<String> f = service.submit(new TestCall());
String s = f.get();
System.out.println(s);
service.shutdown();
FutureTask<String> task = new FutureTask<>(new TestCall());
Thread thread = new Thread(task);
thread.start();
System.out.println("task.get()" + task.get());
}
}