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)); } } }
时间: 2024-10-01 11:13:18