其實多線程也很好理解,就好比我們坐高鐵、飛機過安檢一樣,過安檢的時候一個入口只有一個安檢口,而多線程就是為安檢開啟了多個安檢口,話不多說貼代碼
線程實現的三種方式:
一、繼承Thread類創建線程類
1、定義Thread子類,重寫run()方法,把需要做線程操作的類容放入該方法體中。
2、創建Thread子類的實例,在實例中調用線程對象的start()啟動線程方法,此方法也是代表線程數量的方法,需要啟動多個線程時,只需要調用多次則以。
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().start(); new FirstThreadTest().start();
} } }
}
上述代碼中Thread.currentThread()方法返回當前正在執行的線程對象,getName()方法返回線程名稱。
二、通過Runnable接口創建線程類,這也是常用的一種
1、定義runnable接口實現類,並重寫run()方法,此方法跟繼承Thread類中的run是一樣的
2、創建實現類的實例,並在實例中創建Thread對象,該對象也是代表線程數量的對象,啟動多個線程只需要多次調用對象的start()方法則以。
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(); } } } }
三、通過線程池實現多線程,這個是做常用的也是最實用的
1、通過ExecutorService來管理線程池,並且初始化線程數量
2、定義隊列來存放線程池
3、循環判斷線程是否執行還是睡眠
import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestThread { // 首先初始化ExecutorService線程池,用來管理多線程,設置線程數量 private static ExecutorService pool = Executors.newFixedThreadPool(50); // 定義Queue隊列,用來存放線程池,Runnable就是線程對象 private static Queue<Runnable> queue = new ConcurrentLinkedDeque<>(); // 類加載執行多線程 static { (new TestThread()).new ThreadPoolInvoke().start(); } private class ThreadPoolInvoke extends Thread{ @Override public void run() { // 死循環一直判斷隊列 while (true) { try { // 如果為空,線程睡眠3秒 if (queue.isEmpty()) { Thread.sleep(1000 * 3); } // 如果不為空則執行任務,定義excute方法 excute(); } catch (Exception e) { // TODO: handle exception } } } } /** * 設置線程到隊列方法 * @param runnable */ public static void setTask(Runnable runnable) { queue.add(runnable); } /** * 執行線程任務 */ private void excute() { //為了確保線程安全,這里可以設置同步鎖,this表示當前進入者 //synchronized (this) { // 獲取queue隊列size int curLen = queue.size(); for (int i = 0; i < curLen; i++) { // poll 方法表示從隊列中刪除第一個元素 Runnable item = queue.poll(); // 然后把對象交給多線程處理 pool.execute(item); } //} } }
好了,今天的多線程分享就到這,是否學會了呢?