1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public class SignTest { public static void main(String[] args) { Drama drama = new Drama(); new Thread(new Actor(drama)).start(); new Thread(new Audience(drama)).start(); } }
class Actor extends Thread { Drama drama;
public Actor(Drama drama) { this.drama = drama; }
@Override public void run() { int n = 1; for (int i = 0; i < 30; i++) { if (i % 3 == 0) { this.drama.playDrama("West Word S" + n++); } else { this.drama.playDrama("Ads time"); } } } }
class Audience extends Thread {
Drama drama;
public Audience(Drama drama) { this.drama = drama; }
@Override public void run() { for (int i = 0; i < 30; i++) { drama.watchDrama(); } } }
class Drama { String name; boolean flag = true;
public synchronized void playDrama(String name) { if (!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Actor play " + name); this.notify(); this.name = name; this.flag = !this.flag; }
public synchronized void watchDrama() { if (flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Audience watch " + name); this.notify(); this.flag = !this.flag; } }
|