2016-07-07 1 views
1

以下のコードで、アプリケーションが実行されている可能性があります。しかし、特定のスレッドに通知する方法。 私の仕事はサーバーオブジェクトのすべてのスレッドを印刷していますmsg文字列が文字列の場合msgが変更されました。私は一度サーバーメッセージ文字列ごとに5秒を変更Javaの特定のスレッドに通知する方法

class Thread_test { 
    static String[] name = null ; 

    public static void main(String[] args) throws InterruptedException { 
     Server ser = new Server(); 
     for (int i = 0 ; i < 5 ; i++){ 
      MyThread t1 = new MyThread(ser); 
      t1.setName("Thread "+i); 
     } 
     while(true){ 
      Thread.sleep(5000); 
      ser.sendMsg("Msg : current time is = " + System.currentTimeMillis());  
     } 
    } 

class MyThread extends Thread { 
    Server ser ; 
    public MyThread(Server ser) { 
     this.ser = ser ; 
     this.start(); 
    } 
    public void run() { 
     ser.proccess(); 
    } 
} 

メインメタ():

class Server{ 
    static String msg; 

    synchronized void setMsg(String msg){ 
     this.msg = msg ; 
     notifyAll(); 
    } 

    synchronized void proccess(){ 
     while(true){ 
      try { 
       wait(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      System.out.println(Thread.currentThread().getName()+" : "+Server.msg); 
     } 
    } 
} 

は、ここに私のスレッドクラスです。私が電話するメッセージを変更するときnotifyAll()。このnotifyallはすべての待ちスレッドを起動します。しかし、私が欲しいのは、すなわち:私は10スレッドを作成し、setName Thread_1 Thread_2 ..など。今、Thread_1、Thread_4、Thread_9のようなスレッドに通知したい。私はException in thread "main" java.lang.IllegalMonitorStateException

はあなたが提供することができます任意の助けを事前にありがとうございましたFUNC

 while(true){ 
      Thread.sleep(5000); 
      ser.sendMsg("Msg : current time is = " + System.currentTimeMillis()); 
      for (Thread t : Thread.getAllStackTraces().keySet()){ 
       if(t.getName().equals("Thread_1") || t.getName().equals("Thread_4") || t.getName().equals("Thread_9")){ 
        t.notify(); 
       } 
      } 
     } 

下にしてみてください。

+0

'Object'で宣言された' notify'メソッドを参照している場合は、スレッドに_notify_しないでください。実際にはどういう意味ですか? –

+0

どのラインが例外ですか? –

+0

例外行:t.notify() –

答えて

0
class Server{ 
    String msg; 

    void sendMsg(String msg){ 
     this.msg = msg ; 
    } 
    public void proccess() throws InterruptedException{ 
     while(true){ 
      synchronized (Thread.currentThread()) { 
       Thread.currentThread().wait();   
      } 
      System.out.println(Thread.currentThread().getName()+" : "+this.msg); 
     } 
    } 
} 

クラスオブジェクトwait()を外し、Thread.wait()を追加し、私はそれが正しい戦争かそうでないかわからない

synchronized(t){ 
    t.notify(); 
} 

を追加します。それが間違っていると効率的な方法を提供する。

関連する問題