gpt4 book ai didi

java - 切换到主线程

转载 作者:行者123 更新时间:2023-11-30 06:06:47 25 4
gpt4 key购买 nike

我想知道是否可以以某种方式从我创建的辅助线程移动到我的主线程。辅助线程重复运行,但是,我使用的 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 是无法避免的,总会有一个,而且它总是必须做同样的事情

最佳答案

您有一个(主)工作线程,该线程从计时器线程接收任务(Runnable)并执行它们。

这两个线程(定时器和工作线程)通过队列进行交互;计时器推送任务,工作人员轮询队列并运行它们。如果没有发送任务,则主线程在任务队列中等待。

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

<小时/>

在代码中,

package stackOv;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Threads {

public static void main(String[] args) {
Threads o = new Threads();
System.out.println("main thread is: " + Thread.currentThread().getName());
o.mainThreadRun();
}

// the timer will push tasks to the queue
// the main thread will execute tasks from this queue
// (the main thread should be the only worker!)
BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();

// the main thread executes this
void mainThreadRun() {
// the main thread starts the timer
threadB();

while (!Thread.interrupted()) {
try {
// waits for a task to become available
// if the queue is empty, waits until a task is submitted
Runnable task = tasks.take();
// execute the task
task.run();
} catch (InterruptedException e) {
System.out.println("interrupted");
return;
}
}
}

// executed in the main thread; spawns a timer
void threadB() {
Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
try {
tasks.put(new Runnable() {
@Override
public void run() {
doSomeStuff();
}
});
} catch (InterruptedException e) {
System.out.println("error");
}
}
};
t.schedule(tt, 1000, 1000);
}

void doSomeStuff() {
System.out.println("doSomeStuff: executing from thread=" + Thread.currentThread().getName());
}
}

关于java - 切换到主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51123350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com