Lock对象和synchronized关键字的区别

public class TestLock {

	public static void main(String[] args) throws Exception {
		MyList2 list = new MyList2();
		Thread t1 = new Thread(new Runnable(){
			public void run(){
				list.add("C");
			}
		});
		Thread t2 = new Thread(new Runnable(){
			public void run(){
				list.add("D");
			}
		});
		t1.start();
		t2.start();
		
		t1.join();
		t2.join();
		list.add("E");
		list.print();
	}

}
class MyList2{
	String[] data = {"A","B","","","",""};
	int index = 2;
	Lock lock = new ReentrantLock();		//创建Lock对象	控制多线程同步的锁
	
	public void add(String s){
		try{
			
			//synchronized 的坏处  死锁问题  线程死等
			lock.lock();	//上锁 对锁对象调用lock方法 进入同步代码块
			//lock.tryLock();	//尝试拿锁  提高并发效率  不会阻塞线程  返回值true/false
			//lock.tryLock(long time,TimeUnit unit);	//给线程一个等待的时间
			data[index] = s ; 
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			index++;
		}
		finally{
			lock.unlock();	//解锁	对锁对象调用unlock方法 离开同步代码块
		}
	}
	public void print(){
		for(int i = 0 ; i < data.length ; i++){
			System.out.println(data[i]);
		}
	}
}

在这里插入图片描述

在这里插入图片描述

这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!!!

猜你喜欢

转载自blog.csdn.net/taiguolaotu/article/details/107762712