diff --git a/Java高级特性 - 多线程练习题.txt b/Java高级特性 - 多线程练习题.txt new file mode 100644 index 0000000..c38bef4 --- /dev/null +++ b/Java高级特性 - 多线程练习题.txt @@ -0,0 +1,64 @@ +package step1; + +public class Task { + public static void main(String[] args) throws Exception { + /********* Begin *********/ + // 在这里创建线程, 开启线程 + + Object a = new Object(); + Object b = new Object(); + Object c = new Object(); + // 在这里创建线程, 开启线程 + MyThread th1 = new MyThread("AA", a, c); + MyThread th2 = new MyThread("BB", c, b); + MyThread th3 = new MyThread("CC", b, a); + + th1.start(); + Thread.sleep(10); + th2.start(); + Thread.sleep(10); + th3.start(); + Thread.sleep(10); + System.exit(0); + + /********* End *********/ + } +} + +class MyThread extends Thread { + /********* Begin *********/ + + String threadName; + Object a = null; + Object b = null; + + public MyThread(String threadName, Object a, Object b) { + super(); + this.threadName = threadName; + this.a = a; + this.b = b; + } + + public synchronized void run() { + + int count = 5; + while (count > 0) { + synchronized (a) { + synchronized (b) { + System.out.println("Java Thread" + this.threadName); + count--; + b.notify(); + + } + try { + a.wait(); + } catch (InterruptedException e) { + // TODO 自动生成的 catch 块 + e.printStackTrace(); + } + } + } + + } + /********* End *********/ +}