以下不论哪一种方法,归根结底就是一种,就是new Thread()。
1、继承Thread类,调start方法
public class MainThread {
public static void main(String[] args) {
new MyThread().start();
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("输出,,,,,,");
}
}
2、实现Runnable接口
public class MainThread {
public static void main(String[] args) {
new Thread(new MyRun()).start();
}
}
class MyRun implements Runnable {
@Override
public void run() {
System.out.println("dadfadfadsfsdfasdf");
}
}
3、线程池
public class MainThread {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new MyRun());
// executorService.submit(new MyRun());
executorService.shutdown();
}
}
class MyRun implements Runnable {
@Override
public void run() {
System.out.println("dadfadfadsfsdfasdf");
}
}
ps:使用execute和submit都可以,两者都是异步的,两者的区别在于有没有返回值,execute没有返回值,submit返回值是Future
4、实现Callable接口
public class MainThread {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<String> f = executorService.submit(new MyCall());
System.out.println(f.get());
System.out.println("执行完毕");
executorService.shutdown();
}
}
class MyCall implements Callable<String>{
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "wwdfwdfwf";
}
}
ps: f.get()是个阻塞方法。
5、使用FutureTask
public class MainThread {
public static void main(String[] args) throws Exception {
FutureTask<String> ft = new FutureTask(new MyCall());
new Thread(ft).start();
System.out.println(ft.get());
}
}
class MyCall implements Callable<String>{
@Override
public String call() throws Exception {
return "wwdfwdfwf";
}
}
ps:thread里面不能直接传Callable,所以需要FutureTask来做中间载体,有点设计模式里的适配器概念。
6、使用lambda表达式
public class MainThread {
public static void main(String[] args) throws Exception {
new Thread(()->{
System.out.println("ddddddd");
}).start();
}
}
ps:感觉就是对Runnable的简化,个人不太喜欢这种。