to treeroot(根根)晕死,根本就不存在同步问题,线程之间毫无影响
==============================================
Productor  和 Customer 是根据 Share 来同步的啊

解决方案 »

  1.   

    他们都各自有自己的实例,怎么同步.
    举个例子:房子A和B都是两房一厅加一个卫生间.
    张三和李四住同住A房,此时卫生间公用
    如果张三住A房,李四住B房,他们需要公用吗?
      

  2.   

    to treeroot(根根)
    他们都各自有自己的实例,怎么同步.
    ===================================
    同步对象都是同一个s 啊
      

  3.   


    guten Tag帮你调试过了,把if(!writeable)和if(writeable)分别改成while(!writeable)和while(writeable),问题就解决了。---------------------------------------------public class Share {
    private char c='=';
    private boolean writeable = true;

    public synchronized void write(char c){ while(!writeable) {
    try{
    wait();
    }catch(Exception e){
    e.printStackTrace();
    }
    } this.c = c;
    writeable = false;
    notifyAll();
    }

    public synchronized void print(){

    while(writeable){
    try{
    wait();
    }catch(Exception e){
    e.printStackTrace();
    }
    }

    System.out.println(c);
    writeable = true;
    notifyAll();
    }
    }import java.util.Random;
    public class Productor extends Thread {
    private Share s;
    public Productor(Share s){
    this.s = s;
    }
    public void run(){
    for (char c = 'a'; c <= 'z'; c++) {
    Random r = new Random();
        int i = (int)r.nextInt(5000)  ;
        try {
         sleep(i);
        }catch(Exception e){
         e.printStackTrace();
        }
    s.write(c);
    }
    }
    }import java.util.Random;public class Customer extends Thread {
    private Share s;

    public Customer(Share s){
    this.s = s;
    }

    public void run(){
    for (int i = 0; i < 26; i++) {
    Random r = new Random();
        int j = (int)r.nextInt(5000) ;
        try {
         sleep(j);
        }catch(Exception e){
         e.printStackTrace();
        }
    s.print();
    }

    }

    }public class ThreadDriver { public static void main(String[] args) {
    Share s = new Share();
    Productor p1 = new Productor(s);
    Productor p2 = new Productor(s);
    Customer  c1 = new Customer(s);
    Customer  c2 = new Customer(s);
    Customer  c3 = new Customer(s);
    p1.start();
    p2.start();
    c1.start();
    c2.start();
    c3.start();

    }
    }
      

  4.   

    在Notify的时候,可能是c1 notify 了同类c2,这时c2从wait()中返回,不管writeable是真是假就往屏幕上打字符了,所以导致错误。
    所以醒来时还要检查一次writeable(把if改成while),确保它是被productor唤醒的。
      

  5.   

    to Hannibals(热恋中的德国兵) 谢谢你,  但是这样是不行的 :)
      

  6.   

    to Hannibals(热恋中的德国兵) 
    ================================
    我仔细调试了,你说得有道理,你是对的。在Notify的时候,可能是c1 notify 了同类c2,这时c2从wait()中返回,不管writeable是真是假就往屏幕上打字符了,所以导致错误。
    所以醒来时还要检查一次writeable(把if改成while),确保它是被productor唤醒的。