import java.lang.*; 
import java.util.*; public class helloout 
{ /** 
* @param args 
*/ 
public static void main(String[] args) 
{ Thread th1=new mythread(); 
th1.start(); 
Thread th2=new mythread(); 
th2.start(); 
Thread th3=new mythread(); 
th3.start(); } } class mythread  extends Thread 

private static String str="C"; 
private static int i=0; 
public mythread() 
{ } 
public synchronized void run() 

try{ 
while(i <10) 

notifyAll(); 
if(str.endsWith("C")) 

System.out.println("A"); 
str=str + "A"; 
wait();

if(str.endsWith("A")) 

System.out.println("B"); 
str=str + "B"; 
wait();

if(str.endsWith("B")) 

System.out.println("C"); 
str=str + "C"; 
i++; 
wait();



catch(Exception e) 

} } 
} 本来是想循环输出A,B,C,A,B,C这种顺序10次, 
但是程序不循环,只输出了一次,接触多线程不久,不知道发生了什么, 

解决方案 »

  1.   

    答非所问,但还是要指出来 public class helloout 
    类名称应该大写
      

  2.   

    public class Test { /**
     * @param args
     */ public static void main(String[] args) {
    Thread th1 = new mythread(1);
    th1.start();
    Thread th2 = new mythread(2);
    th2.start();
    Thread th3 = new mythread(3);
    th3.start();
    }
    }class mythread extends Thread {
    public static String str = "C";
    private static int i = 0;
    private int id = 0; public mythread(int id) {
    this.id = id;
    } public void run() {
    try {
    // 三个线程要使用同一个共享对象来进行加锁和解锁.
    // 方法前面使用synchronized使用的是当前对象来加锁, 所以三个不同的线程他们的对象锁是不一样的.
    synchronized (this.getClass()) {
    while (i < 10) {
    this.getClass().notifyAll();
    if (str.endsWith("C")) {
    System.out.println("ID:" + id + ", Times:" + i + " : A");
    str = str + "A";
    this.getClass().wait();
    } if (str.endsWith("A")) {
    System.out.println("ID:" + id + ", Times:" + i + " : B");
    str = str + "B";
    this.getClass().wait();
    } if (str.endsWith("B")) {
    System.out.println("ID:" + id + ", Times:" + i + " : C");
    str = str + "C";
    i++;
    this.getClass().wait();
    } }
    }
    } catch (Exception e) {
    e.printStackTrace();
    } }}
      

  3.   

    为了使得结果更直观, 修改了点代码, 输出结果如下:
    ID:1, Times:0 : A
    ID:2, Times:0 : B
    ID:1, Times:0 : C
    ID:3, Times:1 : A
    ID:1, Times:1 : B
    ID:2, Times:1 : C
    ID:3, Times:2 : A
    ID:2, Times:2 : B
    ID:1, Times:2 : C
    ID:3, Times:3 : A
    ID:1, Times:3 : B
    ID:2, Times:3 : C
    ID:3, Times:4 : A
    ID:2, Times:4 : B
    ID:1, Times:4 : C
    ID:3, Times:5 : A
    ID:1, Times:5 : B
    ID:2, Times:5 : C
    ID:3, Times:6 : A
    ID:2, Times:6 : B
    ID:1, Times:6 : C
    ID:3, Times:7 : A
    ID:1, Times:7 : B
    ID:2, Times:7 : C
    ID:3, Times:8 : A
    ID:2, Times:8 : B
    ID:1, Times:8 : C
    ID:3, Times:9 : A
    ID:1, Times:9 : B
    ID:2, Times:9 : C