**
Java多线程的4种实现方式
**
1:继承Thread并重写run方法,并调用start方法
/**
* Java实现多线程的方式1
* 继承Thread类,重写run方法
* @author hongbo.zhao 2019年4月12日 上午7:12:35
*/
class MyThread extends Thread {
@Override
public void run() {
//此处为thread执行的任务内容
System.out.println(Thread.currentThread().getName());
}
}
public class Demo03 {
public static void main(String[] args) {
for(int i=0;i<2;i++) {
Thread t = new MyThread();
//输出:
//Thread-0 Thread-1
t.start();
}
}
}
2:实现Runnable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法
/**
* Java实现多线程的方式2
* 实现Runnable接口
* @author hongbo.zhao 2019年4月12日 上午7:12:35
*/
class MyThread implements Runnable {
@Override
public void run() {
//此处为thread执行的任务内容
System.out.println(Thread.currentThread().getName());
}
}
public class Demo03 {
public static void main(String[] args) {
for(int i=0;i<2;i++) {
Thread t = new Thread(new MyThread());
//输出:
//Thread-0 Thread-1
t.start();
}
}
}
3:实现Callable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法
/**
* Java实现多线程的方式3
* 实现Callable接口
* @author hongbo.zhao 2019年4月12日 上午7:12:35
*/
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
return null;
}
}
public class Demo03 {
public static void main(String[] args) {
for(int i=0;i<2;i++) {
//创建MyThread实例
Callable<Integer> c = new MyThread();
//获取FutureTask
FutureTask<Integer> ft = new FutureTask<Integer>(c);
//使用FutureTask初始化Thread
Thread t = new Thread(ft);
//输出:
//Thread-0 Thread-1
t.start();
}
}
}
4:使用线程池创建
/**
* Java实现多线程的方式4
* 线程池
* @author hongbo.zhao 2019年4月12日 上午7:12:35
*/
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
class MyThread2 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
return 0;
}
}
public class Demo03 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int i=0;i<2;i++) {
executorService.execute(new MyThread());
FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread2());
//输出
// pool-1-thread-1
// pool-1-thread-2
// pool-1-thread-3
// pool-1-thread-4
executorService.submit(ft);
}
executorService.shutdown();
}
}