多线程(JDK1.5的新特性互斥锁)

时间:2023-03-09 08:50:41
多线程(JDK1.5的新特性互斥锁)

多线程(JDK1.5的新特性互斥锁)(掌握)
1.同步
·使用ReentrantLock类的lock()和unlock()方法进行同步
2.通信
·使用ReentrantLock类的newCondition()方法可以获取Condition对象
·需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
·不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
举例:

public static void main(String[] args) {
final UnitTest ut = new UnitTest();
Thread t1 = new Thread(new Runnable() {
public void run() {
while(true){
ut.print1();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
while(true){
ut.print2();
}
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
while(true){
ut.print3();
}
}
});
t1.start();
t2.start();
t3.start();
}
private ReentrantLock r =new ReentrantLock();
Condition c1 = r.newCondition();
Condition c2 = r.newCondition();
Condition c3 = r.newCondition();
private int flag = 1;

public void print1() {

r.lock();
if(flag!=1){
try {
System.out.println("jinru 11");
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("11");
flag=2;
c2.signal();
r.unlock();
}
public void print2() {
r.lock();
if(flag!=2){
try {
System.out.println("jinru 22");
c2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("22");
flag=3;
c3.signal();
r.unlock();
}
public void print3() {
r.lock();
if(flag!=3){
try {
System.out.println("jinru 33");
c3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("33");
flag=1;
c1.signal();
r.unlock();
}