黑马程序员技术交流社区
标题:
黑马程序员JDK1.5新特性互斥锁的使用方法
[打印本页]
作者:
ulddfhv
时间:
2015-4-17 21:16
标题:
黑马程序员JDK1.5新特性互斥锁的使用方法
多线程(JDK1.5的新特性互斥锁)
1.同步
* 使用ReentrantLock类的lock()和unlock()方法进行同步
2.通信
* 使用ReentrantLock类的newCondition()方法可以获取Condition对象
* 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
* 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
package cn.itcast.singleton;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockDemo {
/**
* @param args
*/
public static void main(String[] args) {
final Printer03 p=new Printer03();
new Thread(){ //创建线程
public void run()
{
while(true)
{try {
p.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}}
};
}.start(); //开启线程
new Thread(){
public void run()
{
while(true)
{try {
p.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}}
};
}.start();
new Thread(){
public void run()
{
while(true)
{try {
p.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}}
};
}.start();
}
}
class Printer03{
ReentrantLock r =new ReentrantLock(); //创建线程锁
private Condition c1 =r.newCondition(); //根据锁产生Condition对象
private Condition c2 =r.newCondition();
private Condition c3 =r.newCondition();
private int flag=1; //定义一个变量作为线程等待的条件
public void print1() throws InterruptedException {
r.lock(); //获得锁,线程锁定
if(flag!=1)
{c1.await();} //当flag!=1的时候线程等待
System.out.println("黑");
System.out.println("黑");
System.out.println("黑");
System.out.println("黑");
System.out.println("黑");
flag=2;
c2.signal(); //当flag=2的时候唤醒线程c2
r.unlock(); //解除锁定
}
public void print2() throws InterruptedException {
r.lock();
if(flag!=2)
{c2.await();}
System.out.println("白");
System.out.println("白");
System.out.println("白");
System.out.println("白");
System.out.println("白");
flag=3;
c3.signal();
r.unlock();
}
public void print3() throws InterruptedException {
r.lock();
if(flag!=3)
{c3.await();}
System.out.println("灰");
System.out.println("灰");
System.out.println("灰");
System.out.println("灰");
System.out.println("灰");
flag=1;
c1.signal();
r.unlock();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2