Java线程作为类

时间:2017-12-19 19:02:39

标签: java thread-synchronization

我可以将一个Thread(运行一个类的实例)传递给另一个类,然后另一个类作为Thread运行并处理第一个的第一个类吗?

这是一些示例/解释代码:

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

两个类都实现了runnable,我希望发送者可以自己调用等待,但是接收者会通知它。我尝试了但没有任何反应,发件人仍处于等待状态。

如果需要,我可以提供整个代码。

1 个答案:

答案 0 :(得分:0)

这是一些精简代码,可以完成我认为你要问的代码:

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

}