日期:2014-05-20 浏览次数:20842 次
package cn.luochengor.csdn; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * synchronized * * @Author luochengor * @Date Nov 25, 2011 * @Email luochengor@foxmail.com */ public class Synchronized { /** * @param args */ public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); D d = new D(); exec.execute(new ThreadA(d)); exec.execute(new ThreadB(d)); } } class D { public synchronized void method1() { try { System.out.println("D.method1()"); System.out.println("method-1 start to sleep."); TimeUnit.SECONDS.sleep(1); System.out.println("method-1 wake up."); } catch (InterruptedException e) { System.out.println("method-1 is interrupted."); } } public synchronized void method2() { try { System.out.println("D.method2()"); System.out.println("method-2 start to sleep."); TimeUnit.SECONDS.sleep(3); System.out.println("method-2 wake up."); } catch (InterruptedException e) { System.out.println("method-2 is interrupted."); } } public void unSynchronized() { System.out.println("This is unSynchronized method."); } } class ThreadA implements Runnable { private D d; public ThreadA(D d) { this.d = d; } @Override public void run() { while (!Thread.interrupted()) { try { System.out.println("ThreadA.run start doing method1()."); d.unSynchronized(); d.method1(); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.out.println("ThreadA.run is interrupted."); } } } } class ThreadB implements Runnable { private D d; public ThreadB(D d) { this.d = d; } @Override public void run() { while (!Thread.interrupted()) { try { System.out.println("ThreadB.run start doing method2()."); d.unSynchronized(); d.method2(); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.out.println("ThreadB.run is interrupted."); } } } }