切换到主线程

时间:2018-07-01 12:35:06

标签: java multithreading

我想知道是否可以以某种方式从我创建的辅助线程转移到主线程。 辅助线程反复运行,但是,我使用的API并不真的喜欢我在该辅助线程中执行某些操作,因此我想将这些操作移入我的主线程(不能有无限循环) :

// this is the main thread
void Main() {
    threadB();
}

// gets called from the main thread but creates its own
void threadB() {
    Timer t = new Timer();
    TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            doSomeStuff();
        }
    };
    t.schedule(tt, 10000, 1000);
}

void doSomeStuff() {
    // this function will now be executed in threadB
    // the API hates what happens in this function but ONLY if its in threadB
    // so can i somehow get threadB to make threadA(Main) call this function?
}

提前谢谢!我希望我解释得足够好。 顺便说一句,创建threadB并没有解决办法,总会有一个,并且它总是必须做相同的事情

1 个答案:

答案 0 :(得分:1)

您有一个(主)工作线程,该线程从计时器线程接收任务(var num = Math.floor(Math.random() * (100)) + 1; var running = true; var tries = 1; while(running) { var input = prompt("Take a guess"); if (input == num) { console.log("Correct!"); console.log("Number of tries: " + tries); running = false; }else if (input > num) { console.log("Too big"); }else if (input < num) { console.log("Too small"); } tries++; } ),并执行它们。

这两个线程(计时器和工作程序)通过队列进行交互;计时器推送任务,然后工作程序轮询队列并运行它们。如果未发送任何任务,则主线程将在任务队列上等待。

以下解决方案基于队列;另一种可能性(更“低级”)是在共享对象上使用RunnableObject.wait()在线程之间发送信号。


在代码中,

notify()