Java多執行緒學習心得
阿新 • • 發佈:2018-11-19
執行緒的概念:
大白話的意思就是,執行緒存在於程序中,它主要是為了提程序中CPU(程序有記憶體,執行緒沒有)的利用率,即提高效率。
主執行緒:執行main方法的執行緒,是它產生其他執行緒,通常它是最後結束,因為它要執行關閉其他執行緒的工作,它不會直接關閉其他執行緒,而只是傳送指令過去。
java實現多執行緒的方式
- 繼承Thread類
- 實現Runnable介面
- 實現Callable介面
java基礎學習時實現多執行緒的方式主要學習前面兩種,callable是後面產生的
下面通過一個案例來理解多執行緒:模擬燒水,洗茶杯與泡茶過程
Demo1:
package test; import java.util.concurrent.CountDownLatch; public class ThreadTest { private static boolean isok = false; static final CountDownLatch countdown = new CountDownLatch(1); public static void main(String[] args) { final Object lock = new Object(); Thread washThread = new Thread(new Runnable() { public void run() { for(int i=1;i<=5;i++) { System.out.println("washing:"+i); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } if(i==3) { System.out.println("發出通知"); countdown.countDown(); } } } },"washthread"); Thread boilThread = new Thread(new Runnable() { public void run() { try { countdown.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("收到通知...make tea..."); } },"boilthread"); washThread.start(); boilThread.start(); } }
Demo2:
package test; import java.util.concurrent.CountDownLatch; public class ThreadTest { private static boolean isok = false; static final CountDownLatch countdown = new CountDownLatch(2); public static void main(String[] args) { final Object lock = new Object(); Thread washThread = new Thread(new Runnable() { public void run() { for(int i=1;i<=5;i++) { System.out.println("washing:"+i); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("發出通知"); countdown.countDown(); } },"washthread"); Thread boilThread = new Thread(new Runnable() { public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("收到通知...make tea..."); countdown.countDown(); } },"boilthread"); Thread maketeaThread = new Thread(new Runnable() { public void run() { try { countdown.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("收到通知... 喝茶..."); } },"maketeathread"); washThread.start(); boilThread.start(); maketeaThread.start(); } }