在您创建的线程中,您将需要对您尝试将消息(方法调用)发送到的线程的引用.
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)
| 归档时间: |
|
| 查看次数: |
1025 次 |
| 最近记录: |