synchronized块

原创
2014/09/29 22:44
阅读数 25

synchronized块相对于方法声明加synchronized关键字,更加灵活

例子

public class FetchRunnable implements Runnable{

	private String TAG_1 = new String("TAG_1");//锁this
	private static String TAG_2 = new String("TAG_2");//锁class
	private String TAG_3 = "TAG_3";//锁class
	
	public void run() {
		//runClass();
		//runThis();
		runTag(TAG_1);
		sleep();
		runTag(TAG_2);
		sleep();
		runTag(TAG_3);
	}
	
	private void runClass() {
		synchronized (FetchRunnable.class) {
			System.out.println("run Class");
			sleep();
		}
	}
	
	private void runThis() {
		synchronized (this) {
			System.out.println("run this");
			sleep();
		}
	}
	
	private void runTag(String tag) {
		synchronized (tag) {
			System.out.println(Thread.currentThread().getName() + " run " + tag +" 秒="+Calendar.getInstance().get(Calendar.SECOND));
			sleep();
		}
	}

	private void sleep() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Thread t0 = new Thread(new FetchRunnable());
		Thread t1 = new Thread(new FetchRunnable());
		t0.start();
		t1.start();
	}
}

运行结果

Thread-0 run TAG_1 秒=18
Thread-1 run TAG_1 秒=18
Thread-1 run TAG_2 秒=20
Thread-0 run TAG_2 秒=21
Thread-1 run TAG_3 秒=22
Thread-0 run TAG_3 秒=23
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部