Java多執行緒實現的四種方式
阿新 • • 發佈:2021-06-30
1、繼承Thread類:
1 public class ThreadTest { 2 3 static class ThreadA extends Thread { 4 5 @Override 6 public void run() { 7 System.out.println(Thread.currentThread()); 8 } 9 10 } 11 12 public static void main(String[] args) { 13 ThreadA a1 = newThreadA(); 14 ThreadA a2 = new ThreadA(); 15 a1.start(); 16 a2.start(); 17 } 18 19 }
2、實現Runnable介面:
1 public class RunnableTest { 2 3 static class ThreadRunnable implements Runnable { 4 5 @Override 6 public void run() { 7 8 System.out.println(Thread.currentThread());9 10 } 11 12 } 13 14 public static void main(String[] args) { 15 16 Thread t1 = new Thread(new ThreadRunnable()); 17 Thread t2 = new Thread(new ThreadRunnable()); 18 t1.start(); 19 t2.start(); 20 21 } 22 23}
3、實現Callable介面:
1 public class CallableTest { 2 3 static class ThreadCall implements Callable<String> { 4 5 @Override 6 public String call() throws Exception { 7 System.out.println(Thread.currentThread()); 8 return "ss"; 9 } 10 11 } 12 13 public static void main(String[] args) throws Exception { 14 15 FutureTask<String> ft = new FutureTask<>(new ThreadCall()); 16 System.out.println(ft.get()); 17 Thread t = new Thread(ft); 18 t.start(); 19 } 20 21 }
4、通過執行緒池建立執行緒:
1 public class ExecutorTest { 2 3 private static ExecutorService es = Executors.newCachedThreadPool(); 4 5 static class ThreadExecutor extends Thread { 6 7 @Override 8 public void run() { 9 System.out.println(Thread.currentThread()); 10 } 11 12 } 13 14 public static void main(String[] args) { 15 16 es.execute(new ThreadExecutor()); 17 es.execute(new ThreadExecutor()); 18 19 } 20 21 }