public class Task2 { public synchronized static void doLongTimeTaskA() { System.out.println("name = " Thread.currentThread().getName() ", begain"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("name = " Thread.currentThread().getName() ", end"); } public synchronized static void doLongTimeTaskB() { System.out.println("name = " Thread.currentThread().getName() ", begain"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("name = " Thread.currentThread().getName() ", end"); } public synchronized void doLongTimeTaskC() { System.out.println("name = " Thread.currentThread().getName() ", begain"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("name = " Thread.currentThread().getName() ", end"); }
class ThreadA extends Thread{ private Task2 mTask2; public ThreadA(Task2 tk){ mTask2 = tk; } public void run() { mTask2.doLongTimeTaskA(); } } class ThreadB extends Thread{ private Task2 mTask2; public ThreadB(Task2 tk){ mTask2 = tk; } public void run() { mTask2.doLongTimeTaskB(); } } class ThreadC extends Thread{ private Task2 mTask2; public ThreadC(Task2 tk){ mTask2 = tk; } public void run() { mTask2.doLongTimeTaskC(); } }
Task2 mTask2 = new Task2(); ThreadA ta = new ThreadA(mTask2); ThreadB tb = new ThreadB(mTask2); ThreadC tc = new ThreadC(mTask2); ta.setName("A"); tb.setName("B"); tc.setName("C"); ta.start(); tb.start(); tc.start();
name = A, begain, time = 1487311199783 name = C, begain, time = 1487311199783 name = C, end, time = 1487311200784 name = A, end, time = 1487311200784 name = B, begain, time = 1487311200784 name = B, end, time = 1487311201784
class ThreadA extends Thread{ private Task2 mTask2; public ThreadA(Task2 tk){ mTask2 = tk; } public void run() { mTask2.doLongTimeTaskC(); } } class ThreadB extends Thread{ private Task2 mTask2; public ThreadB(Task2 tk){ mTask2 = tk; } public void run() { mTask2.doLongTimeTaskC(); } }
Task2 mTaska = new Task2(); Task2 mTaskb = new Task2(); ThreadA ta = new ThreadA(mTaska ); ThreadB tb = new ThreadB(mTaskb ); ta.setName("A"); tb.setName("B"); ta.start(); tb.start();
name = A, begain, time = 1487311905775 name = B, begain, time = 1487311905775 name = B, end, time = 1487311906775 name = A, end, time = 1487311906775
class ThreadA extends Thread{ private Task2 mTask2; public ThreadA(Task2 tk){ mTask2 = tk; } public void run() { //mTask2.doLongTimeTaskC(); mTask2.doLongTimeTaskA(); } } class ThreadB extends Thread{ private Task2 mTask2; public ThreadB(Task2 tk){ mTask2 = tk; } public void run() { //mTask2.doLongTimeTaskC(); mTask2.doLongTimeTaskA(); } }
name = A, begain, time = 1487312239674 name = A, end, time = 1487312240674 name = B, begain, time = 1487312240674 name = B, end, time = 1487312241674