package threadTest;
public class MultiThreadShareDemo {
public static void main(String[] args) throws Exception {
Data data = new Data();
Plus p = new Plus(data);
Cut c = new Cut(data);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/**
* 数据包装
* @author jingfn
*
*/
class Data{
private int data;
private boolean flag;
private int count = 2;
public synchronized Data plus(Data dataIns){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dataIns.data = dataIns.data - 1;
dataIns.count = dataIns.count - 1;
System.out.println(Thread.currentThread().getName()+"--plus--------"+dataIns.data+"---"+dataIns.count);
if(dataIns.count <= 0){
dataIns.flag = true;
this.notifyAll();
}
return dataIns;
}
public synchronized Data cut(Data dataIns){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dataIns.data = dataIns.data + 1;
dataIns.count = dataIns.count + 1;
System.out.println(Thread.currentThread().getName()+"--cut--"+dataIns.data+"---"+dataIns.count);
if(dataIns.count >= 2){
dataIns.flag = false;
this.notifyAll();
}
return dataIns;
}
}
/**
* 加线程
* @author jingfn
*
*/
class Plus implements Runnable {
private Data instance;
public Plus(Data instance){
this.instance = instance;
}
public void run(){
while(true){
instance.plus(instance);
}
}
}
/**
* 减线程
* @author jingfn
*
*/
class Cut implements Runnable {
private Data instance;
public Cut(Data instance){
this.instance = instance;
}
public void run(){
while(true){
instance.cut(instance);
}
}
}
4个线程,2个每次加1,两个每次减1
最新推荐文章于 2021-04-12 19:17:26 发布