文章目录 普通方式 wait 与 notifyAll 阻塞队列
普通方式 wait 与 notifyAll
消费者
package abc ; public class Customer extends Thread { @Override public void run ( ) { while ( true ) { synchronized ( Desk . lock) { if ( Desk . maxNum == 0 ) { break ; } else { if ( Desk . foodNum > 0 ) { Desk . foodNum-- ; Desk . maxNum-- ; System . out. println ( "吃饭中,还能吃 " + Desk . maxNum + "个" ) ; Desk . lock. notifyAll ( ) ; } else { try { System . out. println ( "顾客等待" ) ; Desk . lock. wait ( ) ; } catch ( InterruptedException e) { throw new RuntimeException ( e) ; } } } } } }
}
生产者
package abc ; public class Cook extends Thread { @Override public void run ( ) { while ( true ) { synchronized ( Desk . lock) { if ( Desk . maxNum == 0 ) { break ; } else { if ( Desk . foodNum != 0 ) { try { System . out. println ( "厨师等待" ) ; Desk . lock. wait ( ) ; } catch ( InterruptedException e) { throw new RuntimeException ( e) ; } } else { System . out. println ( "厨师做食物" ) ; Desk . foodNum++ ; Desk . lock. notifyAll ( ) ; } } } } }
}
桌子
package abc ; public class Desk { public static int foodNum= 0 ; public static int maxNum= 40 ; public static Object lock= new Object ( ) ;
}
测试类
package abc ; public class Main { public static void main ( String [ ] args) { Cook cook = new Cook ( ) ; Customer customer = new Customer ( ) ; cook. start ( ) ; customer. start ( ) ; }
}
运行结果
厨师做食物
厨师等待
吃饭中,还能吃 4 个
顾客等待
厨师做食物
厨师等待
吃饭中,还能吃 3 个
顾客等待
厨师做食物
厨师等待
吃饭中,还能吃 2 个
顾客等待
厨师做食物
厨师等待
吃饭中,还能吃 1 个
顾客等待
厨师做食物
厨师等待
吃饭中,还能吃 0 个
阻塞队列
Cook生产者
package zu_se ;
import java. util. concurrent. ArrayBlockingQueue ; public class Cook extends Thread ArrayBlockingQueue < String > queue; public Cook ( ArrayBlockingQueue < String > queue) { this . queue = queue; } @Override public void run ( ) { while ( true ) { try { queue. put ( "食物" ) ; System . out. println ( "厨师做饭" ) ; } catch ( InterruptedException e) { throw new RuntimeException ( e) ; } } }
}
Customer消费者
package zu_se ;
import java. util. concurrent. ArrayBlockingQueue ; public class Customer extends Thread { ArrayBlockingQueue < String > queue; public Customer ( ArrayBlockingQueue < String > queue) { this . queue = queue; } @Override public void run ( ) { while ( true ) { try { String food = queue. take ( ) ; System . out. println ( "顾客吃" + " " + food) ; } catch ( InterruptedException e) { throw new RuntimeException ( e) ; } } }
}
测试类
package zu_se ; import java. util. concurrent. ArrayBlockingQueue ; public class Main { public static void main ( String [ ] args) { ArrayBlockingQueue < String > queue= new ArrayBlockingQueue < > ( 3 ) ; Cook cook= new Cook ( queue) ; Customer customer= new Customer ( queue) ; cook. start ( ) ; customer. start ( ) }
}