大家好
最近遇到一道考试题不太会做 特请各位指教
题目如下
编写一个class printMain 满足下列运行结果
java printMain titi toto tata 
显示为
titi
toto
tata
titi
toto
tata
即是无限循环显示上述三个字符串(或多个,由printMain后的参数表决定)
要求 每一个参数的输出由一个独立的线程负责 所以对于上例既是三个线程
我已经用sleep()方法实现但老师坚持要求用wait()/notify() 完成 并且提供了以下实现方式
类 printThread 继承 Thread 拥有一个指向下一线程的指针
在run方法中应该有:
打印字符串
使当前线程暂停
通知下一线程开始打印但是我编了三天也无法实现
以下是run()的代码public void run(){
synchronized(this){
print();

try {
wait();
} catch (InterruptedException e) {

e.printStackTrace();
}

next.notify();


}


}
在主类中分别建立三个线程 设定好next线程 依次start() 但只能打印一次 无法循环 我知道一定是wait和notify使用上的问题
但是实在是想不出答案 恳请各位给看一下 最好有段代码 谢谢
 

解决方案 »

  1.   

    自己解决了:)
    发上代码大家点评一下
    class printTpublic class printT extends Thread{

    private printT next;

    private String chaine;

            private boolean ok=false;

    public printT(String chaine) throws InterruptedException{

    this.chaine=chaine;
    }

    public void setNext(printT t){
    next=t;
    }

    public void setOk(boolean b){
    ok=b;
    }
    public void print(){
    System.out.println(chaine);
    }

    public synchronized void run(){
    while(true){
    if(ok==true){
    print();

    setOk(false);
    next.setOk(true);

    //activiter l'element suivant
    try {
    synchronized(next){
    next.notify();}
            wait();
    } catch (InterruptedException e) {

    e.printStackTrace();
    }

    }else{

    try {
    wait();
    } catch (InterruptedException e) {                                   e.printStackTrace();
    }
    }


    }
    }

    }类PtMain
    public class PtMain extends Thread{
    public static void main (String [] args) throws InterruptedException{



    if(args.length!=0){

    int taille=args.length;

    printT [] pList=new printT[taille];
    for(int i=0;i<taille;i++){
    pList[i]=new printT(args[i]);
    }

    for(int i=0;i<taille-1;i++){
    pList[i].setNext(pList[i+1]);
    }

    pList[taille-1].setNext(pList[0]);


    for(int i=0;i<taille;i++){
    pList[i].start();
    }

    pList[0].setOk(true);

    }

    }
    }