标签:pre ext 安全 ted zed main tac nbsp div
线程安全:
线程安全的方法一定是排队运行的。
public class SyncObject { synchronized public void methodA() { try { System.out.println("begin methodA threadName = " + Thread.currentThread().getName()); Thread.sleep(5000); System.out.println("end"); } catch (InterruptedException e) { e.printStackTrace(); } } } public class SyncThreadA extends Thread{ private SyncObject object; public SyncThreadA(SyncObject object) { this.object = object; } @Override public void run() { super.run(); object.methodA(); } } public class SyncThreadB extends Thread{ private SyncObject object; public SyncThreadB(SyncObject object) { this.object = object; } @Override public void run() { super.run(); object.methodA(); } } public class ThreadRunMain { public static void main(String[] args) { testSyncThread(); } public static void testSyncThread(){ SyncObject object = new SyncObject(); SyncThreadA a = new SyncThreadA(object); a.setName("A"); SyncThreadB b = new SyncThreadB(object); b.setName("B"); a.start(); b.start(); } }
运行结果:
如果去掉synchronized,运行结果:
标签:pre ext 安全 ted zed main tac nbsp div
原文地址:http://www.cnblogs.com/AK47Sonic/p/7710062.html