- public class ProducerConsumer {
- public static void main(String[] args) {
- Resouse account = new Resouse() ;
- Producer producer = new Producer(account) ;
- Consumer consumer = new Consumer(account);
-
- Thread t1 = new Thread(producer);
- Thread t2 = new Thread(producer);
- Thread t3 = new Thread(consumer);
- Thread t4 = new Thread(consumer);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
- class Resouse {
- int sum = 0 ;
- Boolean flag = false;
- synchronized void save(){
- if(flag){
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else {
- notifyAll();
- flag = true ;
- sum++ ;
- System.out.println("producer"+sum);
- }
- }
-
- synchronized void out(){
- if(!flag){
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else {
- notifyAll();
- flag = false ;
- System.out.println("consumer<<<"+sum);
- }
- }
- }
- class Producer implements Runnable{
- Resouse account ;
- public Producer(Resouse account ){
- this.account = account ;
- }
- public void run(){
- for(int i=0;i<100;i++){
- account.save();
- }
- }
- }
- class Consumer implements Runnable{
- Resouse account ;
- public Consumer(Resouse account ){
- this.account = account ;
- }
- public void run(){
- for(int i=0;i<100;i++){
- account.out();
- }
- }
- }
复制代码 大部分时候结果小于100,有时还大于100. |
|