简体   繁体   English

在java中进行线程化

[英]Threading in java

I have created a one child thread and now i want to send some message from child thread to main thread. 我创建了一个子线程,现在我想从子线程向主线程发送一些消息。 how can i do this? 我怎样才能做到这一点?

In the Thread you created, you will need a reference to the thread you are trying to send the message (method call) to. 在您创建的线程中,您将需要对您尝试将消息(方法调用)发送到的线程的引用。

IE IE

MainClass.java: 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();
    }
}

YourThread.java 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!");
    }
}

使用Callable接口而不是Runnable

There is no parent-child relationship between threads. 线程之间没有父子关系。

A thread can spawn another thread, and once spawned, the 2 threads are independent from each other. 一个线程可以产生另一个线程,并且一旦产生,这两个线程彼此独立。

Please let us know what you mean by send a message . 发送消息告诉我们您的意思。 That can encompass a wide range of use cases, and each has its best implementations. 这可以涵盖广泛的用例,每个用例都有其最佳实现。

For example, if you want to synchronize 2 threads, you can go ahead and use a simple wait / notify mechanism. 例如,如果要同步2个线程,可以继续使用简单的等待/通知机制。 For this, you will have to share an object between the 2. 为此,您必须在2之间共享一个对象。

If you want to compute a value in the spawned thread and pass it back, then you can use queues. 如果要在生成的线程中计算值并将其传回,则可以使用队列。 But you will have to also tell us more about how the execution of the 2 threads is related so that we can suggest the appropriate way to implement it. 但是您还必须告诉我们更多关于2个线程的执行是如何相关的,以便我们可以建议实现它的适当方式。 (Such as producer-consumer mechanism) (如生产者 - 消费者机制)

public class MyClass {
    private MyInterface delegate;

    public void setDelegate(MyInterface delegate) {
        this.delegate = delegate;
    }

    // this will be performed in a background thread
    public void doStuff() {

        Future<String> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return "hello world";
            }
        });

        delegate.handleResponse(future.get());
    }
}

public interface MyInterface {
    void handleResponse(String value);
}

public class MainClass implements MyInterface {

    public static void main(String[] args) {
        MyClass myClass = new MyClass();

        myClass.setDelegate(this);
        myClass.doStuff();
    }

    @Override
    public void handleResponse(String value) {

        // this will be on the main thread
        System.out.println(value);
    }
}

Used Priority queue as the object on which the parent (Main thread) and child thread communicate. 使用优先级队列作为父(主线程)和子线程通信的对象。 Definition of the child runnable 儿童可运行的定义

class CommunicationThead implements Runnable{
    Queue<String> commQueue=null; 
    CommunicationThead(Queue<String> q){
        super();
        this.commQueue=q;
    }
    public void run(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("child :interuppted on sleep");
        }
        synchronized(commQueue){
            if(commQueue!=null)
            {
                commQueue.add("Yo");
                System.out.println("message added by child");
            }
            commQueue.notifyAll();
        }
    }
}

Calling the child runnable (called in the main()) the main thread waits till it receives a message from the child thread 调用子runnable(在main()中调用)主线程等待直到它从子线程接收到消息

Queue<String> q=new PriorityQueue<String>();
Thread child=new Thread(new CommunicationThead(q));
child.start();
boolean msgReceived=true;
while(msgReceived){
    synchronized(q){
        if(q.isEmpty())
        {
            try {
                System.out.println("parent: queue empty | parent waiting");
                q.wait(1000);
            } catch (InterruptedException e) {
                System.out.println("parent wait interrupted");
            }
        }
        else{
            System.out.println("parent found message :"+q.poll());
            msgReceived=false;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM