public class Test { public static void main(String[] args) { new Thread() { @Override public void run() { try { wasteTime("thread1");// } catch (Exception e) { e.printStackTrace(); } } }.start(); new Thread() { @Override public void run() { try { wasteTime("thread2"); } catch (Exception e) { e.printStackTrace(); } } }.start(); } public static Object o = new Object(); public static void wasteTime(String threadName){ System.out.println(threadName + " 进入"); synchronized (o) { try { for (int i = 0; i < 5; i++) { System.out.println(threadName + " 正在执行中"); Thread.sleep(2000); } } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(threadName + " 执行完毕"); } }
敲黑板(大多数人会犯错):synchronized关键字可以锁住的是任意全局对象,只需要保证另一个进入此synchronized代码块时候拿不到这个对象即可。因此锁住的synchronized代码块内的代码逻辑跟这个锁对象没有任何关系。很多人会误认为只有先锁住这个对象,再操作这个对象才是正确的姿势,其实这样理解是不对的。