1. 程式人生 > >實現執行緒的方法的四種方式

實現執行緒的方法的四種方式

Java多執行緒實現的方式有四種

  • 1.繼承Thread類,重寫run方法
  • 2.實現Runnable介面,重寫run方法,實現Runnable介面的實現類的例項物件作為Thread建構函式的target
  • 3.通過Callable和FutureTask建立執行緒
  • 4.通過執行緒池建立執行緒

方式1:繼承Thread類:

public class ThreadOne extends Thread{ public ThreadOne(){ } public void run(){ System.out.println(Thread.currentThread().getName()); } public static void main(String[] args){ ThreadOne threadOne = new ThreadOne(); threadOne.setName("繼承Thread的方式實現執行緒"); threadOne.start(); System.out.println(Thread.currentThread().toString()); } }
方式2:通過實現Runnable介面 :
public class ThreadTwo { public static void main(String[] args){ System.out.println(Thread.currentThread().getName()); Thread t1 = new Thread(new MyThread()); t1.start(); } } class MyThread implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->通過實現介面的方式實現執行緒"); } }

方式3:通過Callable和FutureTask建立執行緒 

public class ThreadThree { public static void main(String[] args) { Callable<Object> callable = new Tickets<Object>(); FutureTask<Object> task = new FutureTask<Object>(callable); Thread t = new Thread(task); System.out.println(Thread.currentThread().getName()); t.start(); } } 
class Tickets<Object> implements Callable<Object>{ @Override public Object call() throws Exception { System.out.println(Thread.currentThread().getName()+"-->通過實現Callable介面通過FutureTask包裝器來實現的執行緒"); return null; } }

方式4:通過執行緒池建立執行緒

public class ThreadFour{ private static int POOL_NUM = 10; public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(5); for(int i = 0; i<POOL_NUM; i++) { RunnableThread thread = new RunnableThread(); executorService.execute(thread); }  executorService.shutdown(); } } class RunnableThread implements Runnable { @Override public void run(){ System.out.println("通過執行緒池方式建立的執行緒:" + Thread.currentThread().getName()); } }