创建线程的四种方式分别是:继承Thread类、实现Runnable接口、通过ExecutorService和Callable<Class>实现有返回值的线程、基于线程池
1.实现Runnable接口
OneThread类
public class OneThread implements Runnable {
@Override
public void run() {
System.out.println("6666666666666666666666666666666666");
}
}
Test类
void test26() throws ExecutionException, InterruptedException {
OneThread oneThread = new OneThread();
Thread thread = new Thread(oneThread);
thread.start();
}
控制台输出
6666666666666666666666666666666666
2.继承Thread类
TwoThread类
public class TwoThread extends Thread {
@Override
public void run() {
System.out.println("777777777777777777777777777777");
}
}
Test类
void test26() throws ExecutionException, InterruptedException {
TwoThread twoThread = new TwoThread();
twoThread.start();
}
控制台输出
777777777777777777777777777777
3.通过ExecutorServie和Callable<Class>实现有返回值的线程
ThreeThread类
public class ThreeThread implements Callable<String> {
private String name;
public ThreeThread(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
return name;
}
}
Test类
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future> list = new ArrayList<Future>();
for (int i =0; i< 5; i++){
Callable c = new ThreeThread(i+"");
Future future = executorService.submit(c);
System.out.println("submit a callable thread:"+i);
list.add(future);
}
executorService.shutdown();
for (Future future : list){
System.out.println("get the result from callable thread:"+ future.get().toString());
}
控制台输出
submit a callable thread:0
submit a callable thread:1
submit a callable thread:2
submit a callable thread:3
submit a callable thread:4
get the result from callable thread:0
get the result from callable thread:1
get the result from callable thread:2
get the result from callable thread:3
get the result from callable thread:4
4.基于线程池
Test类
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i =0; i<10;i++){
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"is running");
}
});
}
控制台输出
pool-1-thread-1is running
pool-1-thread-4is running
pool-1-thread-3is running
pool-1-thread-2is running
pool-1-thread-5is running
pool-1-thread-6is running
pool-1-thread-7is running
pool-1-thread-8is running
pool-1-thread-9is running
pool-1-thread-10is running