多线程循环打印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();

     }

}

猜你喜欢

转载自blog.csdn.net/fighterGuy/article/details/82834617