兩個線程,交替執行
阿新 • • 發佈:2017-05-25
rac notify zed 等待 main java exc start system
import java.util.*; public class Main { static ArrayList<Integer> list=new ArrayList<Integer>(); private static Object lock=new Object(); private static int a=1; private static int b=1; static boolean bool=true; public static void main(String[] args) { Thread t1=new Thread(){ public void run() { for(int i=0;i<10;i++) { synchronized(lock) { a*=3; list.add(a); bool=false; lock.notify();//喚醒一個線程 try { lock.wait();//掛起該線程 } catch(InterruptedException e) { e.printStackTrace(); } } } } }; Thread t2=new Thread(){ public void run() { for(int i=0;i<10;i++) { synchronized(lock){ if(bool) { try{ lock.wait(); } catch(InterruptedException e) { e.printStackTrace(); } } b*=7; list.add(b); bool=true; lock.notifyAll();//喚醒所有等待線程(同一個鎖上) } } } }; t1.start(); t2.start(); try { t1.join(); t1.join(); } catch(InterruptedException e) { e.printStackTrace(); } for(int i=0;i<list.size();i++) { System.out.println(list.get(i)); } } }
兩個線程,交替執行