多线程学习---线程锁的应用(十一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/havebeenstand/article/details/83587889

Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也应该是一个对象。两个线程执行的代码片段要实现同步互斥的效果,它们必须使用同一个Lock对象。锁是上在代表要操作资源的类的内部方法中,而不是线程的代码中!

示例代码:

public class LockStudy {

	public static void main(String[] args) {
		 final Output o = new Output();
			//启动两个线程
			new Thread(new Runnable() {
				@Override
				public void run() {
					while(true){
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						o.printName("wangjinglong");
					}
				}
			}).start();
			new Thread(new Runnable() {
				@Override
				public void run() {
					while(true){
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						o.printName("123456");
					}
				}
			}).start();
		
	}
}
class Output{
	private Lock lock = new ReentrantLock();
	public  void  printName(String name){
		lock.lock();
		for(int i = 0;i < name.length();i++){
			System.out.print(name.charAt(i));
		}
		System.out.println();
		lock.unlock();
	}
}

猜你喜欢

转载自blog.csdn.net/havebeenstand/article/details/83587889