交叉输出字符串A或B,各输出若干次

Posted 菜鸟小文

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了交叉输出字符串A或B,各输出若干次相关的知识,希望对你有一定的参考价值。

 1 public class DBTools {
 2 
 3     private volatile boolean flag = false;
 4 
 5     public synchronized void backupA(){
 6         try {
 7             while(flag){    //当为true阻塞
 8                 this.wait();
 9             }
10 
11             for (int i = 0; i < 5; i ++){
12                 System.out.println("AAAAAAAA");
13             }
14 
15             flag = true;
16             this.notifyAll();
17         } catch (InterruptedException e) {
18             e.printStackTrace();
19         }
20     }
21 
22     public synchronized void backupB(){
23         try {
24             while(!flag){    //当为false阻塞
25                 this.wait();
26             }
27 
28             for (int i = 0; i < 5; i ++){
29                 System.out.println("BBBBBBBB");
30             }
31 
32             flag = false;
33             this.notifyAll();
34         } catch (InterruptedException e) {
35             e.printStackTrace();
36         }
37     }
38 }
 1 public class ThreadA extends Thread{
 2 
 3     private DBTools dbTools;
 4 
 5     public ThreadA(DBTools dbTools){
 6         this.dbTools = dbTools;
 7     }
 8 
 9     @Override
10     public void run() {
11         dbTools.backupA();
12     }
13 }
 1 public class ThreadB extends Thread{
 2 
 3     private DBTools dbTools;
 4 
 5     public ThreadB(DBTools dbTools){
 6         this.dbTools = dbTools;
 7     }
 8 
 9     @Override
10     public void run() {
11         dbTools.backupB();
12     }
13 }
 1 public class Run {
 2 
 3     public static void main(String[] args) {
 4         DBTools tools = new DBTools();
 5         for (int i = 0; i < 10; i ++){
 6             ThreadA a = new ThreadA(tools);
 7             a.start();
 8 
 9             ThreadB b = new ThreadB(tools);
10             b.start();
11         }
12     }
13 }

备注:来源于书籍(高洪岩)Java多线程编程核心技术-177页

以上是关于交叉输出字符串A或B,各输出若干次的主要内容,如果未能解决你的问题,请参考以下文章

运算符

Python运算符与基本数据类型

算数运算符

Python学习之路运算符

运算符

运算符集锦