线程间通信之等待通知

通模拟备份A数据、备份B数据 来实现线程交替运行。方法加synchronized 实现同步

  • 创建工具类设置变量控制线程交替出现
     package com.dairuijie.thread.test01;
    /**
     - 
     - @ClassName:  DBUtils   
     - @Description:TODO(实现备份交替运行)   
     - @author: drj 
     - @date:   2019年7月21日 下午10:17:51   
     -     
     - @Copyright: 2019 
     -  */
    public class DBUtils {
    
    	volatile private boolean flag = true;
    
    	public synchronized void backUpA() {
    		try {
    			while (flag == true) {
    				wait();
    			}
    		    System.out.println("备份A数据库");
    			flag = true;
    			notifyAll();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	public synchronized void backUpB() {
    		try {
    			while (flag == false) {
    				wait();
    			}
    			System.out.println("备份B数据库");
    			flag = false;
    			notifyAll();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    `
  • 创建备份A数据库线程
package com.dairuijie.thread.test01;
/**
 * 
 * @ClassName:  BackUpA   
 * @Description:TODO(备份A 数据)   
 * @author: drj 
 * @date:   2019年7月21日 下午10:22:57   
 *     
 * @Copyright: 2019 
 *
 */
public class BackUpA extends Thread {

	private DBUtils utils;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		utils.backUpA();
	}
	public BackUpA(DBUtils utils) {
		super();
		this.utils = utils;
	}

}

  • 备份B 数据库线程
package com.dairuijie.thread.test01;
/**
 * 
 * @ClassName:  BackUpB   
 * @Description:TODO(备份B 线程)   
 * @author: drj 
 * @date:   2019年7月21日 下午10:20:53   
 *     
 * @Copyright: 2019 
 *
 */
public class BackUpB extends Thread {

	private DBUtils utils;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		utils.backUpB();
	}
	public BackUpB(DBUtils utils) {
		super();
		this.utils = utils;
	}

}

  • 测试
package com.dairuijie.thread.test01;

public class Demo {
	public static void main(String[] args) {
		DBUtils db = new DBUtils();
		for (int i = 0; i < 10; i++) {
			BackUpA a = new BackUpA(db);
			a.start();
			BackUpB b = new BackUpB(db);
			b.start();
		}
	}
}

  • 效果
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库
    备份B数据库
    备份A数据库

猜你喜欢

转载自blog.csdn.net/qq_29897369/article/details/96774391