java建立執行緒的四種方式
阿新 • • 發佈:2019-01-29
參考自:http://blog.csdn.net/longshengguoji/article/details/41126119
java建立執行緒的三種方式
1. 繼承Thread類建立執行緒類
package com.thread; public class FirstThreadTest extends Thread{ int i = 0; //重寫run方法,run方法的方法體就是現場執行體 public void run() { for(;i<100;i++){ System.out.println(getName()+" "+i); } } public static void main(String[] args) { for(int i = 0;i< 100;i++) { System.out.println(Thread.currentThread().getName()+" : "+i); if(i==20) { new FirstThreadTest().run(); new FirstThreadTest().run(); } } } }
2. 通過Runable介面建立執行緒類
package com.thread; public class RunnableThreadTest implements Runnable { private int i; public void run() { for(i = 0;i <100;i++) { System.out.println(Thread.currentThread().getName()+" "+i); } } public static void main(String[] args) { for(int i = 0;i < 100;i++) { System.out.println(Thread.currentThread().getName()+" "+i); if(i==20) { RunnableThreadTest rtt = new RunnableThreadTest(); new Thread(rtt,"新執行緒1").start(); new Thread(rtt,"新執行緒2").start(); } } } }
3. 通過Callable和FutureTask建立執行緒
a. 建立Callable介面的實現類,並實現call()方法;b. 建立Callable實現類的例項,使用FutureTask類來包裝Callable物件,該FutureTask物件封裝了該Callback物件的call()方法的返回值;
c. 使用FutureTask物件作為Thread物件的target建立並啟動新執行緒;
d. 呼叫FutureTask物件的get()方法來獲得子執行緒執行結束後的返回值。
package com.demo; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class CallableThreadTest implements Callable<Integer> { public static void main(String[] args) { CallableThreadTest ctt = new CallableThreadTest(); FutureTask<Integer> ft = new FutureTask<Integer>(ctt); // Thread thread = new Thread(ft,"有返回值的執行緒"); // thread.start(); for(int i = 0;i < 100;i++) { System.out.println(Thread.currentThread().getName()+" 的迴圈變數i的值"+i); if(i==20) { new Thread(ft,"有返回值的執行緒").start(); } } try { System.out.println("子執行緒的返回值:"+ft.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } @Override public Integer call() throws Exception { int i = 0; for(;i<100;i++) { System.out.println(Thread.currentThread().getName()+" "+i); } return i; } }
4. 通過執行緒池建立執行緒
/**
*
*/
package com.demo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Maggie
*
*/
public class ThreadPool
{
/* POOL_NUM */
private static int POOL_NUM = 10;
/**
* Main function
*/
public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int i = 0; i<POOL_NUM; i++)
{
RunnableThread thread = new RunnableThread();
executorService.execute(thread);
}
}
}
class RunnableThread implements Runnable
{
private int THREAD_NUM = 10;
public void run()
{
for(int i = 0; i<THREAD_NUM; i++)
{
System.out.println("執行緒" + Thread.currentThread() + " " + i);
}
}
}