package cglib;java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;ide
public class jiekou{
private int j;
private Lock lock=new ReentrantLock();
public static void main(String args[]){
jiekou jiekou =new jiekou();
jiekou.Add a=jiekou.new Add();
jiekou.Subtract b=jiekou.new Subtract();
System.out.println("線程:"+Thread.currentThread().getName());
for(int i=0;i<2;i++){
Thread aa=new Thread(a);
aa.start();
Thread bb=new Thread(b);
bb.start();
}
System.out.println("線程和:"+Thread.currentThread().getName());
}
private class Add implements Runnable{線程
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<2;i++){
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+": "+"j++="+j++);
}finally{
lock.unlock();
}
}
}
}
private class Subtract implements Runnable{get
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<2;i++){
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+": "+"j--="+j--);
}finally{
lock.unlock();
}
}
}
}
class
}import
輸出:im
線程:main
Thread-0: j++=0
Thread-0: j++=1
Thread-1: j--=2
Thread-1: j--=1
線程和:main
Thread-3: j--=0
Thread-3: j--=-1
Thread-2: j++=-2
Thread-2: j++=-1static