簡體   English   中英

在java中進行線程化

[英]Threading in java

我創建了一個子線程,現在我想從子線程向主線程發送一些消息。 我怎樣才能做到這一點?

在您創建的線程中,您將需要對您嘗試將消息(方法調用)發送到的線程的引用。

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

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

線程之間沒有父子關系。

一個線程可以產生另一個線程,並且一旦產生,這兩個線程彼此獨立。

發送消息告訴我們您的意思。 這可以涵蓋廣泛的用例,每個用例都有其最佳實現。

例如,如果要同步2個線程,可以繼續使用簡單的等待/通知機制。 為此,您必須在2之間共享一個對象。

如果要在生成的線程中計算值並將其傳回,則可以使用隊列。 但是您還必須告訴我們更多關於2個線程的執行是如何相關的,以便我們可以建議實現它的適當方式。 (如生產者 - 消費者機制)

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

使用優先級隊列作為父(主線程)和子線程通信的對象。 兒童可運行的定義

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

調用子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