Java實現兩個執行緒交替列印問題
阿新 • • 發佈:2019-01-26
執行緒1負責列印a,b,c,d
執行緒2負責列印1,2,3,4
要求控制檯中輸出的內容為 a1b2c3d4
package com.sdmjhca.springBootDemo.countdownlatch; /** * @author JHMI on 2017/8/28. */ public class TestMain { static final Object object = new Object(); public static void main(String[] args) throws InterruptedException { new Thread(newRunnable() { String a[] = {"a","b","c","d"}; @Override public void run() { for(int i=0;i< 4 ;i++){ synchronized (object){ System.out.println("執行緒a 開始執行"); object.notify(); try { System.out.println("執行緒a 開始等待"); object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("執行緒a 繼續執行"); System.out.println(a[i]); System.out.println("執行緒a 執行結束"); object.notify(); } } } }).start();new Thread(new Runnable() { int a[] = {1,2,3,4}; @Override public void run() { for(int i=0;i<4;i++){ synchronized (object){ System.out.println("執行緒1 開始執行"); object.notify(); try { System.out.println("執行緒1 開始等待"); object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("執行緒1 繼續執行"); System.out.println(a[i]); System.out.println("執行緒1 執行結束"); } } } }).start(); } }