1. 程式人生 > >多執行緒迴圈列印A B C D。。。。

多執行緒迴圈列印A B C D。。。。

class ProducerThread1 extends Thread {

     private UserEntity userEntity;

     public ProducerThread1(UserEntity userEntity) {

           this.userEntity = userEntity;

     }

     @Override

     public void run() {

           int count = 0;

           while (true) {//此處可以修改為迴圈的次數,下面列印的while判斷改成一樣的判斷條件就可以

            synchronized

(userEntity) {

                     if(userEntity.flag) {

                           try

{

                                userEntity.wait();

                           } catch (InterruptedException e) {

                                e.printStackTrace();

                           }

                     }

                     if (count == 0) {

                           userEntity.username = "A";

                     } else if(count == 1){

                            userEntity.username = "B";

                    }else {

                           userEntity.username = "C";

                     }

                     count = (count + 1) % 3;  //此處需要列印幾個,就修改數字,並在上面if中進行判斷

                    userEntity.flag = true;

                     userEntity.notify();

                }

           }

     }

}

class ConsumerThread1 extends Thread {

     private UserEntity userEntity;

     public ConsumerThread1(UserEntity userEntity) {

           this.userEntity = userEntity;

     }

     @Override

     public void run() {

           while (true) {

                synchronized (userEntity) {

                     if(!userEntity.flag) {

                           try {

                                userEntity.wait();

                           } catch (InterruptedException e) {

                                e.printStackTrace();

                           }

                     }

                     System.out.println("username:" + userEntity.username ;

                     userEntity.flag = false;

                     userEntity.notify();

                }

           }

     }

}

public class ConsumerAndProducerDemo2 {

     public static void main(String[] args) {

           UserEntity userEntity = new UserEntity();

           ProducerThread1 producerThread = new ProducerThread1(userEntity);

           producerThread.start();

           ConsumerThread1 consumerThread = new ConsumerThread1(userEntity);

           consumerThread.start();

     }

}