- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个简单的 Java GUI,带有启动和停止按钮。我使用启动按钮来运行线程,使用停止按钮来停止它。线程启动正常,但我无法用停止按钮停止它。这是我的一段代码:
这是图形界面的类:
public class GridController implements ActionListener {
// Definisco la vista
private final GridView vista;
acqreg acq;
public GridController(final GridView vista) {
this.vista = vista;
}
@Override
public void actionPerformed(final ActionEvent e) {
Object src = e.getSource();
String ID = null;
String IP = null;
if (src == this.vista.startacqButton) {
// Reset di tutte le Label di errore
this.resetLabels();
// Check degli input sui campi
if (this.checkAllInputs()) {
// CONTROLLO CAMPI ANDATO A BUON FINE
System.out.println("Campi Compilati Correttamente");
// Inibisco le pressioni successive del bottone start
this.vista.startacqButton.setEnabled(false);
// Inibisco la modifica dei campi inseriti sul form
this.vista.getcbIDphidget().setEnabled(false);
this.vista.gettfMiscela().setEnabled(false);
this.vista.gettfLotto().setEnabled(false);
this.vista.gettfDataop().setEnabled(false);
// Riattivo lo stop button
this.vista.stopacqButton.setEnabled(true);
// POSSO FAR PARTIRE L'ACQUISIZIONE -----------------------------------------------------------------------------------------------------------------
try {
// Recupero la coppia ID Scheda - IP Scheda dal file conf
BufferedReader phidgetip = new BufferedReader(new FileReader("PhidgetsIP.conf"));
String riga;
while ( (riga = phidgetip.readLine()) != null){
String[] parts = riga.split("#");
String part1 = parts[0]; // ID Phidget
String part2 = parts[1]; // IP Phidget
if (part1.equals(this.vista.cbIDphidget.getSelectedItem())) {
ID = part1;
IP = part2;
// Creo oggetto per l'acquisizione
acq = new acqreg(ID , IP , vista);
//Avvio il thread
acq.start();
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(GridController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GridController.class.getName()).log(Level.SEVERE, null, ex);
}
// Ho trovato l'ID giusto --> apro il canale di comunicazione
}else{
System.out.println("Alcuni campi non sono stati compilati correttamente");
}
}else if(src == this.vista.stopacqButton ){
// Inibisco le pressioni successive del bottone stop
this.vista.stopacqButton.setEnabled(false);
// Riattivo lo start button
this.vista.startacqButton.setEnabled(true);
// Inibisco la modifica dei campi inseriti sul form
this.vista.getcbIDphidget().setEnabled(true);
this.vista.gettfMiscela().setEnabled(true);
this.vista.gettfLotto().setEnabled(true);
this.vista.gettfDataop().setEnabled(true);
// Stoppo l'acquisizione
acq.interrupt();
}
}
}
...这是运行线程“acq”的类。
public class acqreg extends Thread {
private final String ID;
private final String IP;
private final GridView vista;
public acqreg(String ID , String IP, GridView vista){
this.IP=IP;
this.ID = ID;
this.vista=vista;
}
public void run() {
stopped=false;
try{
//.....do something.....
//dichiarazione variabili di acquisizione
final long start = System.nanoTime();
int seriale;
double tempDevice;
double tempAmbiente;
long prg = 1;
//Ciclo di acquisizione
while (!stopped) {
// ....do the long work....
Thread.sleep(1000);
}
}
}catch(Exception ex){
}
}
@Override
public void interrupt() {
stopped=true;
}
我认为问题在于我定义线程对象“acq”的位置(在 try catch block 中):
// Creo oggetto per l'acquisizione
acq = new acqreg(ID , IP , vista);
//Avvio il thread
acq.start();
因为当我尝试停止线程时:
else if(src == this.vista.stopacqButton ){
.......some code.........
// Stoppo l'acquisizione
acq.interrupt();
interrupt()方法没有启动,线程继续运行!在 Debug模式下,我在“acq.interrupt()”行出现此错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
最佳答案
实际上有几个问题:
1) 你的代码格式太糟糕了...至少使用一些可以满足你要求的 IDE。
2)你的类命名不好。请遵守命名约定。类名以“C”大写字母开头。
3) 最好不要使用方法名称“interrupt()”。更糟糕的是,永远不要在 Thread/Runnable 类中重写此方法!除非在那里调用 super.interrupt() 这会导致严重的问题!因为 Interrupt() 正是可以让 sleep() 脱离暂停的一件事。
4)至少做一些基本的异常处理,你不应该忽略异常,除非你确切地知道你在做什么,然后它应该被注释!
这里有一个小例子,展示了一个相当不错的工作线程应该是什么样子。它将所有与线程相关的内容从调用者手中夺走,并仅授予对 startThread() 和 stopThread() 方法的访问权限。这样就不会受到外部的错误干扰。
/**
* This worker can only run once
* @author JayC667
*/
public class ProperThreading {
private final Thread mThread = new Thread(() -> runWorkingLoop()); // if you want worker to be able to run multiple times, move initialisation into startThread()
private volatile boolean mThreadStarted = false;
private volatile boolean mStopRequested = false;
private final long mLoopSleepTime;
public ProperThreading(final long pLoopSleepTime /* pass more arguments here, store in members */ ) {
mLoopSleepTime = pLoopSleepTime;
}
public synchronized void startThread() {
if (mThreadStarted) throw new IllegalStateException("Worker Thread may only be started once and is already running!");
mThreadStarted = true;
mThread.start();
}
private void runWorkingLoop() {
while (!mStopRequested /* && other checks */ ) {
try {
// do the magic work here
Thread.sleep(mLoopSleepTime);
} catch (final InterruptedException e) {
break;
} catch (final Exception e) {
// do at least some basic handling here, you should NEVER ignore exception unless you know exactly what you're doing, and then it should be commented!
}
}
}
public synchronized void stopThread() {
if (!mThreadStarted) throw new IllegalStateException("Worker Thread is not even running yet!");
mStopRequested = true;
mThread.interrupt();
}
}
关于java - 无法检索 Java 线程来停止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36822222/
如果我使用下面的代码,数据将为零 dispatch_async(dispatch_get_global_queue(0,0), ^{ UIImage *img = [[UIImage allo
fread来自 data.table包一般可以在读取文件时自动确定列分隔符( sep )。 例如,这里fread自动检测 |作为列分隔符: library(data.table) fread(past
因此,如果我有一个如下所示的数据框: A B C rowname1 4.5 4 3.2 rowname2 3 23
我有一个汽车模型的搜索数据库:“日产Gtr”,“Huynday Elantra”,“Honda Accord”等。 现在我还有一个用户列表和他们喜欢的汽车类型 user1喜欢:carId:1234,c
我正在使用 Javamail 来获取一些电子邮件数据。我将用户输入作为电子邮件 ID、imap 地址和密码并连接到 imap。然后我监视收件箱的电子邮件并查明此人是否在“收件人”或“抄送”中。 Ema
我有一些数据,我想根据差距统计来评估最佳簇数。 我阅读了 gap statistic 上的页面在 r 中给出了以下示例: gs.pam.RU Number of clusters (method '
我有一个用户名和密码组合,我将使用它通过 java 代码访问安全服务器。 我的想法是: 在外部存储加密凭据 执行时提示用户输入解密密码 在使用前将解密的凭据直接存储在字符数组中 使用凭据连接到数据库
这是 Firebase 数据:[Firebase 数据][1] 我必须从员工那里检索所有字段并将其存储在一个数组中。 现在数据更改 toast 消息即将到来,但已经很晚了。 Firebase.setA
我是 iOS 的新手,正在开发一个基本的应用程序,它目前正在使用 SSKeychain 和 AFNetworking 与 API 进行交互。当您使用我检索的应用程序登录并在我的 CredentialS
编辑:这个问题已经在 apphacker 和 ConcernedOfTunbridgeWells 的帮助下得到解决。我已更新代码以反射(reflect)我将使用的解决方案。 我目前正在编写一个群体智能
我是 C 的新手,我想编写一个程序来检查用户输入的单词是否合法。我已经在 stackoverflow 上搜索了建议,但很多都是针对特定情况的。请在我被激怒之前,我知道这个语法不正确,但正在寻找一些关于
我相信你们中的一些人编写过 C# 类,这些类必须从数据库设置密码/从数据库获取密码。 我假设敏感细节不会以明文形式显示。处理此类数据的推荐程序是什么?检索到的文本是否加密?您是否将 pws 存储在加密
我在 linux 上使用 2.7 之前的 python 版本,想知道如何检索 RUID? 2.7 及更高版本从 os 包中获得了 getresuid,但我似乎找不到 2.6 的等效项 最佳答案 您可以
我已经在 Android 中实现了一个存储对象的标准 LRUCache。每个键都是与存储的对象关联的唯一 ObjectId。我的问题是从缓存中检索对象的唯一方法是通过 ObjectId(无迭代器)。实
这已经被问过很多次了。解决方案(对我有用)是从 packages.config 文件(这就足够了)和 packages 文件夹中删除 *** 包。 这对我来说是一个糟糕的解决方案,因为每次我想安装一些
我有以下文字: #{king} for a ##{day}, ##{fool} for a #{lifetime} 以及以下(损坏的)正则表达式: [^#]#{[a-z]+} 我想匹配所有#{word
我正在寻找一种快速(如高性能,而不是快速修复)解决方案来持久化和检索数千万个小型(大约 1k)二进制对象。每个对象都应该有一个用于检索的唯一 ID(最好是 GUID 或 SHA)。额外的要求是它应该可
有没有办法获取 RegInit 的重置值?通过探测产生的类型的成员?我可以看到 RegInit 将返回类型(例如 UInt )。例如,我将有一个寄存器,我想通过 regmap 对其进行控制。 val
Iv 目前接手了一个项目,其中开发人员在某些表的 json 数组列中存储了 has many 关系。 产品表 ---------------------------- id | product | c
Git 会在任何地方记录推送到远程的历史吗? 我注意到我们能够在 Microsoft VSTS 中查看 Git 存储库的推送历史记录以及每次推送的相关提交。它甚至显示旧的、过时的提交,由于后来的强制推
我是一名优秀的程序员,十分优秀!