2 synchronized 和 Lock+Condtion 对比

同步两种方式:synchronized关键字            Lock 锁住


package Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
 * 一个线程打印5次,另一个打印3次,交替循环3次
 * 
 * synchronized+ this.wait()+this.notify() 
 *     等于Lock.lock()+unlock()+lock.newCondition()+ await()+signal()
 * 不同的是lock需要手动释放unlock互斥锁,而synchronized不需要
 * 
 * mutex锁只能用于race condition不破坏critical section,
 * 			要具体指定哪个线程访问必须有个flag,也就是这里的isOne
 * */
public class Ex1 {
	public static void main(String[] args){
		//final Run r = new Run();
		final Run2 r = new Run2();
		new Thread(new Runnable(){
			@Override
			public void run() {
				for(int i=0;i<3;i++)
					r.thread1();
			}
		}).start();
		
		new Thread(new Runnable(){
			public void run(){
				for(int i=0;i<3;i++)
					r.thread2();
			}
		}).start();
	}
	
}

class Run{
	private boolean isOne = true;
	synchronized void thread1(){
		while(!isOne){  //一定是循环等待,防止误唤醒
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		for(int i=1;i<=5;i++){
			System.out.println(Thread.currentThread().getName()+":第"+i+"次");
		}
		isOne = false;
		this.notify();
	}
	
	synchronized void thread2(){
		while(isOne){
			try{
				this.wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		for(int i=1;i<=3;i++){
			System.out.println(Thread.currentThread().getName()+":第"+i+"次");
		}
		
		isOne = true;
		this.notify();
	}
	 
}

class Run2{
	boolean isOne = true;
	Lock lock = new ReentrantLock();
	Condition c = lock.newCondition();
	
	void thread1(){
		lock.lock();
		try{
			while(!isOne){
				try{
					c.await();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			
			for(int i=1;i<=5;i++)
				System.out.println(Thread.currentThread().getName()+":第"+i+"次");
			isOne = false;
			c.signal();
		}finally{
			lock.unlock();
		}
	}
	
	void thread2(){
		lock.lock();
		try{
			while(isOne){
				try{
					c.await();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			for(int i=1;i<=3;i++)
				System.out.println(Thread.currentThread().getName()+":第"+i+"次");
			isOne = true;
			c.signal();
			
		}finally{
			lock.unlock();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值