Java两个线程交替打印(实现Runnable接口)

package senTset; //纸张类 public class page{ private boolean isWrite = false; //设置一个公共变量来控制线程执行public synchronized void write1() { while(isWrite) {// 公共变量为true时等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }System.out.print("中"); isWrite = true; notify(); // 唤醒打印“国”的线程 }public synchronized void write2() { while (!isWrite) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }System.out.print("国"); isWrite = false; notify(); // 唤醒打印“中”的线程 }//小红写字 static class xhWrite implements Runnable{ private page page; public xhWrite( page page) { this.page = page; }@Override public void run() { for(int i = 0; i < 10; i++) { page.write1(); } }} //小明写字 static class xmWrite implements Runnable{ private page page; public xmWrite( page page) { this.page = page; } @Override public void run() { for(int i = 0; i < 10; i++) { page.write2(); }}}public static void main(String[] args) { page p = new page(); //小明和小红共用一张纸 xmWrite xm = new xmWrite(p); xhWrite xh = new xhWrite(p); Thread t1=new Thread(xm); Thread t2=new Thread(xh); t1.start(); t2.start(); }}

【Java两个线程交替打印(实现Runnable接口)】就是这样,如果有什么不对的地方希望大家指出

    推荐阅读