Arya GM
Arya GM

Reputation: 81

How to notify certain thread in java

In below code My application run may thread. But How to I notify certain thread. My task is print all the thread from Server object msg String when String msg change.

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);
        }
    }
}

Here is my thread class :

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

Main Meth() :

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());       
        }
    }

I change the Server message string once every 5 sec. When change the message I call notifyAll(). This notifyall is wakeup all the waiting thread. But what I want is i.e : I create 10 thread and setName Thread_1 Thread_2 ..etc., Now I want to notify some thread like Thread_1, Thread_4 and Thread_9. I try below 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();
                }
             }  
        }

I got Exception in thread "main" java.lang.IllegalMonitorStateException

Thank you in advance for any help you can provide.

Upvotes: 1

Views: 1090

Answers (1)

Arya GM
Arya GM

Reputation: 81

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);
        }
    }
}

Remove the class object wait() and add Thread.wait() and add

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

I don't know it is a correct war or Not. If it wrong provide efficient way.

Upvotes: 0

Related Questions