0
  • n o t i f yすべての文字をタブで区切って印刷するプログラムを作成しました。

  • 私はスレッド間通信を使用しました.1つのスレッドが1つの文字を印刷し、別のスレッドが別の文字を印刷し、wait()notify().

  • 出力として取得n o tしています。どうi f yですか?印刷されないのはなぜですか?

コード:

package multi_threading; 

 public class test_value implements Runnable{
    static String name="notify";
    Thread t;
    static int len;
    boolean val=false;
    static int i;
    public test_value(){}
    public test_value(test_value obj,String msg){
        t=new Thread(obj,msg);
        t.start();
    }
    public static void main(String args[]){
        len=name.length();
        test_value obj=new test_value();
        new test_value(obj,"Child1"); 
        new test_value(obj,"Child2");
    }
    public void run(){
        synchronized(this){
          while(i<len){
          System.out.println("I got "+name.charAt(i));
          i++;
          val=!val;
          while(val){
              try{
                   wait();
                }catch(InterruptedException e){
                    System.out.println("Interrupted");
               }
           }
          notify();
        }
      }   
    }
 }
4

3 に答える 3

0

さらに良いことに、val はまったく必要ありません。

synchronized(this){
    while(i<len){
        System.out.println("I got "+name.charAt(i) + ", " + Thread.currentThread().getName());
        i++;    
        try{
            notify();
            wait();
        }catch(InterruptedException e){
            System.out.println("Interrupted");
        }
    }
}   

これを実行して出力を得ました:

I got n, Child2
I got o, Child1
I got t, Child2
I got i, Child1
I got f, Child2
I got y, Child1

受け入れられた回答コードを使用して、出力を得ました:

I got n, Child1
I got o, Child2
I got t, Child2
I got i, Child1
I got f, Child1
I got y, Child2

これは、あなたが望むように真に交互のスレッドではありません。これは、notify が実際にはロックを解除しないことに起因します。これは、ロックを放棄するとき (待機するとき) に、待機中のスレッドの 1 つに実行する番であることを知らせることを意味します。

于 2013-11-08T16:42:16.893 に答える
-1

あなたの変数

boolean val=false;

静的ではないため、各スレッドには独自の値があり、静的にします

static boolean val=false;
于 2013-11-08T15:57:01.590 に答える