代码如下:
public class TestThread{

public class DoThing{
private boolean valueSet = false;
private String name;
private int i;

public synchronized void Set(String name){
if(valueSet)
try{
  wait();
}catch(InterruptedException e){
  System.out.println("InterruptedException e");
}
valueSet = true;
notify();
System.out.println("pub: " + name);  
}

public synchronized String Get(){
if(!valueSet)
  try
  {
    wait();
   }
  catch(InterruptedException e){
   System.out.println("InterruptedException e");
   }
  valueSet = false;
  notify();
  return name + ++i;
}
}

public class Tux implements Runnable{
DoThing t = new DoThing();
  Tux(){
    new Thread(this).start();
  }
  public void run(){
   for(int i = 0;i < 5;i++)
   {
     t.Set("Tux");
   }
  }
}

public class Tux1 implements Runnable{
DoThing t = new DoThing();
Tux1(){
new Thread(this).start();
}
public void run(){
   for(int i = 0;i < 5;i++)
   {
     System.out.println(t.Get());
   }
}
}

public void GetTuxInstance(){
   Tux tux = new Tux();
   Tux1 tux1 = new Tux1();   
}

public static void main(String[] args){
  TestThread t1 = new TestThread();
                  t1.GetTuxInstance();
}
}
其运行后打印出来的值总是在等待,我哪块写错了,谢谢。

解决方案 »

  1.   

    当valueSet变为true之后程序就执行wait等待了,需要用notify唤醒。
      

  2.   

    3KS,嗯,我知道要notiry,但怎样才能让另一个线程发出这个notify消息呢?
      

  3.   

    你用了synchronized(同步),当然是第一个线程把FOR运行完才会运行第二个线程的FOR,第二个线程当然不会及时发notify消息了.
      

  4.   

    不好意思,理解错误.
    下面我为你做了一下修改.
    package testTwo;public class TestThread { public class DoThing {
    private boolean valueSet = false; private String name; private int i; public synchronized void Set(String name) {
    this.name=name;
    if (valueSet)
    try {
    wait();
    } catch (InterruptedException e) {
    System.out.println("InterruptedException e");
    }
    valueSet = true;
    notify();
    System.out.println("pub: " + name);
    } public synchronized String Get() {
    if (!valueSet)
    try {
    wait();
    } catch (InterruptedException e) {
    System.out.println("InterruptedException e");
    }
    valueSet = false;
    notify();
    return name + ++i;
    }
    } public class Tux implements Runnable {
    DoThing t ; Tux(DoThing t) {
    this.t=t;
    new Thread(this).start();
    } public void run() {
    for (int i = 0; i < 5; i++) {
    t.Set("Tux");
    }
    }
    } public class Tux1 implements Runnable {
    DoThing t; Tux1(DoThing t) {
    this.t=t;
    new Thread(this).start();
    } public void run() {
    for (int i = 0; i < 5; i++) {
    System.out.println(t.Get());
    }
    }
    } public void GetTuxInstance() {
    DoThing t = new DoThing();
    Tux tux = new Tux(t);

    Tux1 tux1 = new Tux1(t);
    } public static void main(String[] args) {
    TestThread t1 = new TestThread();
    t1.GetTuxInstance();
    }
    }
    你两个线程都初始化了DoThing,所以两个线程间运行的不是一个DoThing
      

  5.   

    谢谢dryZeng
    明白了。多个线程需要围绕同一个对象进行同步的,我这个理解是吧。