转载请注明出处
http://blog.csdn.net/pony_maggie/article/details/42886735
作者:小马
新建状态(New)
新创建了一个线程对象,但是还没有start。class Blockable extends Thread { private Peeker peeker; protected JTextField state = new JTextField(30); protected int i; public Blockable(Container c) { c.add(state); peeker = new Peeker(this, c); } public synchronized int read() {return i;} protected synchronized void update() { state.setText(getClass().getName() + " state:i = " + i); } public void stopPeeker() { peeker.terminate(); } }
class Peeker extends Thread { private Blockable b; private int session; private JTextField status = new JTextField(30); private boolean stop = false; public Peeker(Blockable b, Container c) { c.add(status); this.b = b; start(); } public void terminate() { stop = true; } public void run() { while(!stop) { status.setText(b.getClass().getName()+ " Peeker " + (++session) + "; value = " + b.read()); try { sleep(100); } catch (InterruptedException e) { System.err.println("Interrupted"); } } } }
class Sleeper1 extends Blockable { public Sleeper1(Container c) {super(c);} public synchronized void run() { while(true) { i++; update(); try { sleep(1000); } catch (InterruptedException e) { System.err.println("Interrupted"); } } } } class Sleeper2 extends Blockable { public Sleeper2(Container c) {super(c);} public void run() { while(true) { change(); try { sleep(1000); } catch (InterruptedException e) { System.err.println("Interrupted"); } } } public synchronized void change() { i++; update(); } }