在java中进行线程化

lea*_*arn 2 java

我创建了一个子线程,现在我想从子线程向主线程发送一些消息.我怎样才能做到这一点?

Pab*_*ruz 7

在您创建的线程中,您将需要对您尝试将消息(方法调用)发送到的线程的引用.

IE

MainClass.java:

public class MainClass implements Runnable
{
    private Queue<String> internalQueue;
    private boolean keepRunning;

    public MainClass()
    {
        keepRunning = true;
        internalQueue = new Queue<String>();
    }

    public void queue(String s)
    {
        internalQueue.add(s);
        this.notify();
    }

    public void run()
    {
         // main thread

         // create child thread
         Runnable r = new YourThread(this);
         new Thread().start(r);

         // process your queue
         while (keepRunning) {
             // check if there is something on your queue
             // sleep
             this.wait();
         }
    }

    public static void main(String[] args)
    {
       MainClass mc = new MainClass();
       mc.run();
    }
}
Run Code Online (Sandbox Code Playgroud)

YourThread.java

public class YourThread implements Runnable
{
    private MainClass main;

    public YourThread(MainClass c)
    {
         this.main = c;
    }

    public void run()
    {
         // your thread starts here
         System.out.println("Queue a message to main thread");
         main.queue("Hi from child!");
    }
}
Run Code Online (Sandbox Code Playgroud)