- public static void main(String[] args) {
- //创建对象
- final MyPrinter p = new MyPrinter();
- //创建线程对象
- new Thread(){
- public void run() {
- //循环执行
- while(true){
- try {
- p.print1();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }.start();
- new Thread(){
- public void run() {
- //循环执行
- while(true){
- try {
- p.print2();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }.start();
- new Thread(){
- public void run() {
- //循环执行
- while(true){
- try {
- p.print3();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }.start();
- }
- }
- class MyPrinter {
- ReentrantLock r = new ReentrantLock(); //获取互斥锁对象 跟syn同步代码块
- Condition c1 = r.newCondition(); //获取等待跟唤醒功能
- Condition c2 = r.newCondition();
- Condition c3 = r.newCondition();
-
- private int t =1;
- public void print1() throws InterruptedException{
- r.lock(); //获取锁 跟synchronized 类似
- if(t!=1){
- c1.await();
- }
- System.out.println("11111");
- t=2;
- c2.signal(); //唤醒线程
- r.unlock(); //释放锁
- }
-
- public void print2() throws InterruptedException{
- r.lock();
- if(t!=2){
- c2.await(); //线程等待
- }
- System.out.println("222222");
- t=3;
- c3.signal(); //唤醒线程
- r.unlock(); //释放锁
- }
-
- public void print3() throws InterruptedException{
- r.lock();
- if(t!=3){
- c3.await();//线程等待
- }
- System.out.println("3333333");
- t=1;
- c1.signal(); //唤醒线程
- r.unlock(); //释放锁
- }
-
复制代码
|
|