gpt4 book ai didi

java - 如何重启线程?

转载 作者:行者123 更新时间:2023-11-29 07:20:57 25 4
gpt4 key购买 nike

它是一个 RMI 服务器对象,可能会运行很多 sethumanActivity(),我如何确保在新的 changeToFalse 运行之前停止或暂停先前的 changeToFalse 线程? t。中断 ?

基本上当调用 sethumanActivity() 时,humanActivity 将被设置为 true ,但将运行一个线程将其设置回 false。但是我在考虑如何在调用另一个 sethumanActivity() 时禁用或终止线程?

public class VitaminDEngine implements VitaminD {

public boolean humanActivity = false;
changeToFalse cf = new changeToFalse();
Thread t = new Thread(cf);


private class changeToFalse implements Runnable{

@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
humanActivity = false;
}

}

@Override
public void sethumanActivity() throws RemoteException {
// TODO Auto-generated method stub
humanActivity = true;
t.start();
}

public boolean gethumanActivity() throws RemoteException {
// TODO Auto-generated method stub
return humanActivity;
}

}

在 SOer 的帮助下编辑

package smartOfficeJava;

import java.rmi.RemoteException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VitaminDEngine implements VitaminD {

public volatile boolean humanActivity = false;
changeToFalse cf = new changeToFalse();
ExecutorService service = Executors.newSingleThreadExecutor();


private class changeToFalse implements Runnable{

@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
humanActivity = false;
}

}

@Override
public synchronized void sethumanActivity() throws RemoteException {
humanActivity = true;
service.submit(cf);
}

public synchronized boolean gethumanActivity() throws RemoteException {
return humanActivity;
}

}

最佳答案

使用 ExecutorService。 ExecutorService 将创建一个线程,您可以根据需要多次向它们提交可运行对象。

ExecutorService service = Executors.newSingleThreadExecutor();

然后在你的代码中

@Override
public void sethumanActivity() throws RemoteException {
// TODO Auto-generated method stub
humanActivity = true;
service.submit(cf);
}

另外,为了正确起见,您正在不安全地写入 humanActivity 字段。存在过时读取的可能性。有很多文章谈论可见性,您可以查看here .

关于java - 如何重启线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4597432/

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