设计4个线程,其中两个线程每次对 j 增加1,另外两个线程对 j 每次减少1。

public class Test_j进程 {
	public static void main(String[] args) {
		
		Printer1 p = new Printer1();
		//th1线程
		Thread th1 = new Thread() {
			@Override
			public void run() {
				try {
					p.printA();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		//th2线程
		Thread th2 = new Thread() {
			@Override
			public void run() {
				try {
					p.printB();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		//th3线程
		Thread th3 = new Thread() {
			@Override
			public void run() {
				try {
					p.printC();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		//th4线程
		Thread th4 = new Thread() {
			@Override
			public void run() {
				try {
					p.printD();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		//启动线程
		th1.start();
		th2.start();
		th3.start();
		th4.start();
	}
	
}

class Printer1{
	private static int flag = 1;
	//静态成员 标志位 取值1
	//1:当前th1执行
	//2:当前th2执行
	//3:当前th3执行
	//4:当前th4执行
	int j = 0;  //前两个线程对j加1,后两个线程对j减1
	
	//printA
	public void printA() throws Exception {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				while (flag != 1) {
					this.wait();  //锁释放,进入等待
				}
				j++;
				System.out.println("printA加1:" + j);
				flag = 2;  //修改标志,让th2执行
				this.notifyAll();  //唤醒另一个线程
			}
		}
	}
	//printB
	public void printB() throws Exception {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				while (flag != 2) {
					this.wait();  //锁释放,进入等待
				}
				j++;
				System.out.println("printB加1:" + j);
				flag = 3;  //修改标志,让th3执行
				this.notifyAll();  //唤醒另一个线程
			}
		}
	}
	//printC
	public void printC() throws Exception {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				while (flag != 3) {
					this.wait();  //锁释放,进入等待
				}
				j--;
				System.out.println("printC减1:" + j);
				flag = 4;  //修改标志,让th4执行
				this.notifyAll();  //唤醒另一个线程
			}
		}
	}
	//printD
	public void printD() throws Exception {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				while (flag != 4) {
					this.wait();  //锁释放,进入等待
				}
				j--;
				System.out.println("printD减1:" + j);
				System.out.println();
				flag = 1;  //修改标志,让th1执行
				this.notifyAll();  //唤醒另一个线程
			}
		}
	}
	
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值