设计4个线程,其中两个线程每次对 j 增加 1 ,另外两个线程对 j 减少 1。
借鉴了生产者消费者案例。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadTest2 {
public static void main(String[] args) {
Resource r=new Resource();
System.out.println(r.j+"");
Add a=new Add(r);
Subtract s=new Subtract(r);
Thread t0=new Thread(a);
Thread t1=new Thread(a);
Thread t2=new Thread(s);
Thread t3=new Thread(s);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
class Resource{
int j;
boolean flag=false;
Lock lock = new ReentrantLock();
Condition con=lock.newCondition();
}
class Add implements Runnable{
Resource r;
public Add(Resource r){
this.r=r;
}
public void run(){
while(true){
try{
r.lock.lock();
while(r.flag){
try{
r.con.await();
}catch(InterruptedException e){ }
}
r.j++;
System.out.println(Thread.currentThread().getName()+":"+r.j);
r.flag=true;
r.con.signalAll();
}finally{
r.lock.unlock();
}
}
}
}
class Subtract implements Runnable{
Resource r;
public Subtract(Resource r){
this.r=r;
}
public void run(){
while(true){
try{
r.lock.lock();
while(!r.flag){
try{
r.con.await();
}catch(Exception e){ }
}
r.j--;
System.out.println(Thread.currentThread().getName()+":"+r.j);
r.flag=false;
r.con.signalAll();
}finally{
r.lock.unlock();
}
}
}
}