Search code examples
javathread-synchronization

Java thread as argument to a class


Can I pass a Thread (which runs an instance of a class) to another class which then runs as a Thread too and handle the first from the second?

This is some sample/explain code:

 Sender sender = new Sender(client, topic, qos,frequency);
 Thread t1;
 t1= new Thread(sender);
 t1.start();


 Receiver receiver = new Receiver(frequency,client, qos, topic,t1);
 Thread t2;
 t2 = new Thread(receiver);
 t2.start();

Both classes implement runnable and I want the sender to call wait himself but the receiver to notify it. I tried it but nothing happens, sender is still in waiting state.

I can provide the whole code if needed.


Solution

  • Here's some stripped down code that does what I think you are asking:

    public class WaitTest {
    
        static class Waiter implements Runnable{
    
            @Override
            public void run() {
                System.out.println("Waiting");
                try {
                    synchronized(this){
                        this.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                System.out.println("Running");
            }
    
        }
    
        static class Notifier implements Runnable{
    
            Object locked;
    
            public Notifier(Object locked){
                this.locked = locked;
            }
    
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                synchronized(locked){
                    locked.notifyAll();
                }
    
            }
    
        }
    
        public static void main(String[] args){
    
            Waiter waiter = new Waiter();
            Notifier notifier = new Notifier(waiter);
    
            Thread t1 = new Thread(waiter);
            Thread t2 = new Thread(notifier);
    
            t1.start();
            t2.start();
        }
    
    }