线程创建的四种方式
- 继承Thread类、
- 实现Runnable接口、
- 实现ThreadFactory接口、
- 使用ExecutorService、Callable、Future实现有返回结果的多线程
1. 继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
System.out.println(this.getId());
}
}
public static void main(String[] args) {
System.out.println("begin main");
MyThread myThread = new MyThread();
myThread.start();
System.out.println("end main");
}
}
2. 实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
System.out.println(Thread.currentThread().getId());
}
}
public static void main(String[] args) {
System.out.println("begin main");
Thread thread = new Thread(new MyRunnable());
thread.start();
System.out.println("end main");
}
}
3. 实现ThreadFactory接口
public class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
public static void main(String[] args) {
MyThreadFactory myFactory = new MyThreadFactory();
System.out.println("begin main");
Thread thread = myFactory.newThread(new MyThread());
thread.start();
System.out.println("end main");
}
}
4.使用ExecutorService、Callable、Future实现有返回结果的多线程
public class MyCallable implements Callable<Object> {
private String name;
public MyCallable(String name) {
this.name = name;
}
@Override
public Object call() throws Exception {
return name;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
int taskSize = 5;
// 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 创建多个有返回值的任务
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable("线程" + i);
// 执行任务并获取Future对象
Future f = pool.submit(c);
// System.out.println(">>>" + f.get().toString());
list.add(f);
}
// 关闭线程池
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从Future对象上获取任务的返回值,并输出到控制台
System.out.println(">>>>" + f.get().toString());
}
}
}
区别
使用第一种方式创建的线程,可以直接使用this调用线程的方法。(this->new MyThread())<创建Thread对象>
使用第二种方式创建的线程,不能直接使用this调用线程方法,MyRunnable只是重写了Runnable接口的run方法,而真正的线程是new Thread(new MyRunnable())时创建,MyRunnable作为Thread构造方法的参数。<用Thread构造方法创建对象>
使用第三种方法创建的线程,借助线程工厂创建,可批量生产一定规格的线程。<用ThreadFactory的newThread方法创建对象>
使用第四种方式创建的线程,ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类,返回结果的线程是在JDK1.5中引入的新特征,确实很实用,有了这种特征我就不需要再为了得到返回值而大费周折了,而且即便实现了也可能漏洞百出。
可返回值的任务必须实现Callable接口,类似的,无返回值的任务实现Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。