1. 程式人生 > >按訂單號(String常量池唯一,即物件唯一)加同步鎖

按訂單號(String常量池唯一,即物件唯一)加同步鎖

package com.mmhlive.bdp.service;

public class TestLock implements Runnable{
	public static void main(String[] args) {
		TestLock tl1=new TestLock("th1");
		TestLock tl2=new TestLock("th2");
		new Thread(tl1).start();
		new Thread(tl2).start();
		
	}
	public TestLock(String name) {
		 this.name=name;
	}
	private String name;
	@Override
	public void run() {
 
		 synchronized ("orderId") {
			System.out.println(name);
			try {
				Thread.sleep(10000000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
 

輸出:th1

package com.mmhlive.bdp.service;

public class TestLock implements Runnable{
	public static void main(String[] args) {
		TestLock tl1=new TestLock("th1");
		TestLock tl2=new TestLock("th2");
		new Thread(tl1).start();
		new Thread(tl2).start();
		
	}
	public TestLock(String name) {
		 this.name=name;
	}
	private String name;
	@Override
	public void run() {
		 Object obj=new Object();
//		 synchronized ("orderId") {
			 synchronized (new String("orderId")) {
			System.out.println(name);
			try {
				Thread.sleep(10000000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
 

輸出:

th1
th2