java 的线程实现自加_【JavaSE学习】创建4个线程,其中2个线程对成员变量i实现自加1,另外两个线程对i实现自减1;...

*****************************************Stor.java************************************************

package com.gem.lesson10.adddec;

class Stor {

private final int Max_Size = 10;

private final int Min_Size = 0;

private int i = 8;

public Stor(){}

public Stor(int cur) {

this.i = cur;

}

public synchronized void add(){

if(this.i >= this.Max_Size){

System.out.println("当前值: " + this.i + "\t将超出最大值,无法自增!");

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.i++;

System.out.println("已完成自加。当前值: " + this.i);

notifyAll();

}

public synchronized void dec(){

if(this.i <= this.Min_Size){

System.out.println("当前值: " + this.i + "\t将超出最大值,无法自增!");

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.i--;

System.out.println("已完成自减。当前值: " + this.i);

notifyAll();

}

}

*****************************************Add.java************************************************

package com.gem.lesson10.adddec;

public class Add extends Thread{

private Stor stor;

Add(){}

Add(Stor stor){

this.stor = stor;

}

public void run() {

this.stor.add();

}

}

*****************************************Dec.java************************************************

package com.gem.lesson10.adddec;

public class Dec extends Thread{

private Stor stor;

Dec(){}

Dec(Stor stor){

this.stor = stor;

}

public void run() {

this.stor.dec();

}

}

*****************************************Adddec.java**********************************************

package com.gem.lesson10.adddec;

public class Adddec{

public static void main(String[] args) {

Stor stor = new Stor(5);

Add a1 = new Add(stor);

Add a2 = new Add(stor);

Add a3 = new Add(stor);

Add a4 = new Add(stor);

Dec d1 = new Dec(stor);

Dec d2 = new Dec(stor);

Dec d3 = new Dec(stor);

Dec d4 = new Dec(stor);

a1.start();

a2.start();

a3.start();

a4.start();

d1.start();

d2.start();

d3.start();

d4.start();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值