Java多线程的4种实现方式
1:继承Thread并重写run方法,并调用start方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class MyThread extends Thread { @Override public void run() { 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(); t.start(); } } }
|
2:实现Runnable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class MyThread implements Runnable { @Override public void run() { 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()); t.start(); } } }
|
3:实现Callable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
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++) { Callable<Integer> c = new MyThread(); FutureTask<Integer> ft = new FutureTask<Integer>(c); Thread t = new Thread(ft); t.start(); } } }
|
4:使用线程池创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
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());
executorService.submit(ft); } executorService.shutdown(); } }
|