1.Java实现多线程的几种方式
继承Thread类
实现Runnable接口
实现Callable接口通过FutureTask包装器来创建Thread线程
使用ExecutorService、Callable、Future实现有返回结果的多线程(使用ExecutorService)来管理前三种方式。
2.继承Thread类
Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例,启动线程的唯一方法是通过Thread类的start()方法,start()方法是一个native方法,它将启动一个新线程,并执行run()方法。
public class MyThread extends Thread {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread1 = new MyThread();
myThread1.start();
3.实现Runnable接口
如果自己的类已经extends了另外一个类,就无法直接extends Thread,此时,可以实现Runnable接口。
public class MyThread extends OtherClass implements Runnable {
public void run() {
System.out.println("MyThread.run()");
}
}//启动 MyThread,需要首先实例化一个 Thread,并传入自己的 MyThread 实例:
MyThread myThread = new MyThread(); Thread thread = new Thread(myThread);
thread.start();
//事实上,当传入一个 Runnable target 参数给 Thread 后, Thread 的 run()方法就会调用
target.run() public void run() {
if (target != null) {
target.run();
}
}
4.ExecutorService Callable Future 有返回值线程
有返回值的任务必须实现Collable接口,类似的,无返回值的任务必须实现Runnable接口。执行Callable任务后,可以获取一个Future对象,在该对象上调用get就可以获取到Callable任务返回的Object。再结合线程池接口ExecutorService就可以实现有返回结果的多线程。
//创建一个线程池
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); list.add(f);
}
// 关闭线程池
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从 Future 对象上获取任务的返回值,并输出到控制台
System.out.println("res: " + f.get().toString());
}
5.基于线程池的方式
线程和数据库连接这些资源都是非常宝贵的,那么每次需要的时候创建,不需要的时候销毁,是非常浪费资源的。所以我们可以使用线程池。
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10); while(true) {
threadPool.execute(new Runnable() {
// 提交多个线程任务,并执行
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running..");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}