3 synchronized和Lcok+Condition对比续

来源:互联网 发布:tensorflow 版本区别 编辑:程序博客网 时间:2024/05/22 11:50
package Test;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/* *  三个线程一个打印1次,一个打印2次,一个打印三次;循环5次  *  *  lock阻塞和synchronized关键字一样,但利用condition可以控制唤醒哪个线程 *  但还是不能没有标志位控制线程的运行顺序,唯一的好处是不用notifyAll * */public class Ex2 {public static void main(String args[]){final Solution2 s = new Solution2();new Thread(new Runnable(){public void run(){for(int i=0;i<5;i++)s.thread1();}}).start();new Thread(new Runnable(){public void run(){for(int i=0;i<5;i++)s.thread2();}}).start();new Thread(new Runnable(){public void run(){for(int i=0;i<5;i++)s.thread3();}}).start();}}class Solution1{int turn = 1;public synchronized void thread1(){while(turn!=1){try{this.wait();}catch(InterruptedException e){}}System.out.println(Thread.currentThread().getName()+"第1次");turn = 2;this.notifyAll();}public synchronized void thread2(){while(turn!=2){try{this.wait();}catch(InterruptedException e){}}for(int i=1;i<=2;i++)System.out.println(Thread.currentThread().getName()+"第"+i+"次");turn = 3;this.notifyAll();}public synchronized void thread3(){while(turn!=3){try{this.wait();}catch(InterruptedException e){}}for(int i=1;i<=3;i++)System.out.println(Thread.currentThread().getName()+"第"+i+"次");turn = 1;this.notifyAll();}}class Solution2{Lock lock = new ReentrantLock();Condition c1 = lock.newCondition();Condition c2 = lock.newCondition();Condition c3 = lock.newCondition();int turn = 1;public void thread1(){lock.lock();try{try {while(turn!=1)c1.await();} catch (InterruptedException e) {}System.out.println(Thread.currentThread().getName()+"第1次");turn = 2;c2.signal();try {c1.await();} catch (InterruptedException e) {}}finally{lock.unlock();}}public void thread2(){lock.lock();try{while(turn!=2)try{c2.await();}catch(InterruptedException e){}for(int i=0;i<2;i++){System.out.println(Thread.currentThread().getName()+"第"+i+"次");try {Thread.sleep(1000);} catch (InterruptedException e) {}}turn = 3;c3.signal();}finally{lock.unlock();}}public void thread3(){lock.lock();try{while(turn!=3)try{c3.await();}catch(InterruptedException e){}for(int i=0;i<3;i++){System.out.println(Thread.currentThread().getName()+"第"+i+"次");try {Thread.sleep(1000);} catch (InterruptedException e) {}}turn = 1;c1.signal();}finally{lock.unlock();}}}

原创粉丝点击