以下のコードで、アプリケーションが実行されている可能性があります。しかし、特定のスレッドに通知する方法。 私の仕事はサーバーオブジェクトのすべてのスレッドを印刷しています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();
}
}
}
下にしてみてください。
'Object'で宣言された' notify'メソッドを参照している場合は、スレッドに_notify_しないでください。実際にはどういう意味ですか? –
どのラインが例外ですか? –
例外行:t.notify() –