Java 线程作为 class 的参数

Java thread as argument to a class

我可以将一个线程(它运行一个 class 的实例)传递给另一个 class,然后它也作为一个线程运行并处理第二个中的第一个吗?

这是一些 sample/explain 代码:

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

这两个 class 都实现了 runnable,我希望发送者自己调用等待,但接收者通知它。我试过了,没有任何反应,发件人还在等待中。

如果需要我可以提供完整的代码。

下面是一些精简代码,可以满足您的要求:

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

}