用线程交换打印#和&10
最后的结果应该是这样的#&#&#&#&的形式  我有sleep()方法会作 
但是我想用synchronized notify() 来做

解决方案 »

  1.   


    public class MyThread {
    private static boolean flag = false; public static void main(String[] args) {
    new Thread(new ThreadA()).start();
    new Thread(new ThreadB()).start();
    } public synchronized void printA() throws Exception {
    while (true) {
    if (flag)
    wait();
    System.out.println("#");
    flag = true;
    notifyAll();
    }
    } public synchronized void printB() throws Exception {
    while (true) {
    if (!flag)
    wait();
    System.out.println("&");
    flag = false;
    notifyAll();
    }
    }
    }class ThreadA implements Runnable {
    private static MyThread myThread = new MyThread(); public void run() {
    try {
    myThread.printA();
    } catch (Exception e) {
    }
    }
    }class ThreadB implements Runnable {
    private static MyThread myThread = new MyThread(); public void run() {
    try {
    myThread.printB();
    } catch (Exception e) {
    }
    }
    }差不多是这样吧,但总是阻塞了。 线程学的不咋样,学习啊
      

  2.   


    public class MyThread {
    private static boolean flag = false; public static void main(String[] args) {
    MyThread myThread = new MyThread();
    new Thread(new ThreadA(myThread)).start();
    new Thread(new ThreadB(myThread)).start();
    } public synchronized void printA() throws Exception {
    while (true) {
    if (flag)
    wait();
    System.out.println("#");
    flag = true;
    notifyAll();
    }
    } public synchronized void printB() throws Exception {
    while (true) {
    if (!flag)
    wait();
    System.out.println("&");
    flag = false;
    notifyAll();
    }
    }
    }class ThreadA implements Runnable {
    private static MyThread myThread; public ThreadA(MyThread myThread) {
     this.myThread = myThread;
    }
    public void run() {
    try {
    myThread.printA();
    } catch (Exception e) {
    }
    }
    }class ThreadB implements Runnable {
    private static MyThread myThread = new MyThread(); public ThreadB(MyThread myThread){
     this.myThread = myThread;
    }

    public void run() {
    try {
    myThread.printB();
    } catch (Exception e) {
    }
    }
    }哈哈,改进了哈,终于可以执行了。
    给我分儿。 这个差不多是一个 生产与消费 的结构