天天看点

java synchronized 示例

在java中以提供synchronized关键字的形式,为防止资源冲突提供了内置支持。当任务要执行被synchronized关键字保护的代码片段的时候,它将检查锁是否可用,然后获取锁,执行代码,最后释放锁。

考虑下面一种场景,多个人同时向打印机打印东西。

下面是程序示例:

package com.lemon.ch02;

public class TestSync {

	public static void main(String[] args) {
		Printer printer =new Printer();
		ExecutePrintThread t1=new ExecutePrintThread(printer,"zhangsan");
		new Thread(t1, "线程A").start();

		ExecutePrintThread t2=new ExecutePrintThread(printer,"lisi");
		new Thread(t2, "线程B").start();
	}

}

class ExecutePrintThread implements Runnable{
	private Printer printer;
	private String content;

	public ExecutePrintThread(Printer printer,String content){
		this.printer=printer;
		this.content=content;
	}
	@Override
	public void run() {
		printer.doPrint(content);
	}
}

class Printer{
	public  void doPrint(String content){
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
		System.out.println(Thread.currentThread().getName()+"当前时间:"+System.currentTimeMillis()+"正在被打印:");
		System.out.print(content);
		System.out.println();
	}
}
           
运行之后,结果可能如下:
java synchronized 示例

显然,这不是我们想要的结果,从打印时间上来看,在同一时间,同一个打印机在打印两份东西。

对于打印机而言,同一时间只能被一个人使用(就是说,同一时间只能打印一份东西),如果要实现这样的效果,需要给打印机执行打印的方法加把锁。

class Printer{
	public synchronized void doPrint(String content){
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
		System.out.println(Thread.currentThread().getName()+"当前时间:"+System.currentTimeMillis()+"正在被打印:");
		System.out.print(content);
		System.out.println();
	}
}
           
其他代码都不用改变,输出如下:
java synchronized 示例