线程依赖Java
我有一个生成线程的主类,让我们称它们为MainClass和MyThread线程依赖Java,java,multithreading,Java,Multithreading,我有一个生成线程的主类,让我们称它们为MainClass和MyThread public class MainClass extends javax.swing.JFrame { int sharedVariable; MyThread threadInstance; public MainClass (){ sharedVariable = 2; threadInstance = new MyThread(this); threadInst
public class MainClass extends javax.swing.JFrame {
int sharedVariable;
MyThread threadInstance;
public MainClass (){
sharedVariable = 2;
threadInstance = new MyThread(this);
threadInstance.run();
}
public int getSharedVariable(){ return sharedVariable; }
public static void main(String[] args){
//begin main class
}
}
public class MyThread implements Runnable {
MainClass class;
public MyThread(MainClass main_class){
this.main_class= main_class;
}
@Override
public run(){
while(this.main_class is still active){
//grab status of sharedVariable and wait for x amount of time.
}
}
}
问题是我不知道如何实现while条件,该条件检查MainClass实例是否仍然处于活动状态,如果仍然处于活动状态,则必须使用this.main\u class.getSharedVariable()来获取sharedVariable的值,然后等待x个时间量。MainClass有main方法。我建议在
main(…)
方法退出之前,先按住threadInstance
实例,然后调用threadInstance.interrupt()
比如:
public static void main(String[] args){
MainClass mainClass = new MainClass();
try {
...
// do main stuff here
...
} finally {
mainClass.threadInstance.interrupt();
}
}
然后在您的线程中,您将执行以下操作:
while(!Thread.currentThread().isInterrupted()){
...
}
您还需要正确处理中断异常:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread here
Thread.currentThread().interrupt();
// if we are interrupted quit
return;
}
顺便说一句,在构建期间将对象实例泄漏到另一个线程是非常糟糕的:
new MyThread(this);
请看这里:
另外,当调用
threadInstance.run()时,您并没有启动线程代码>。您只是在当前线程中运行它。您应该使用threadInstance.start()
,但不能在构造函数内部使用。我建议您按住线程
实例,然后在主(…)
方法退出之前调用threadInstance.interrupt()
比如:
public static void main(String[] args){
MainClass mainClass = new MainClass();
try {
...
// do main stuff here
...
} finally {
mainClass.threadInstance.interrupt();
}
}
然后在您的线程中,您将执行以下操作:
while(!Thread.currentThread().isInterrupted()){
...
}
您还需要正确处理中断异常
:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread here
Thread.currentThread().interrupt();
// if we are interrupted quit
return;
}
顺便说一句,在构建期间将对象实例泄漏到另一个线程是非常糟糕的:
new MyThread(this);
请看这里:
另外,当调用
threadInstance.run()时,您并没有启动线程代码>。您只是在当前线程中运行它。您应该使用threadInstance.start()
,但不要在构造函数内部使用它。您可以使用CountDownLatch
,这对于等待其他线程完成某些活动等任务非常方便(您可以将main中的Thread.sleep(…)
参数更改为12000L,然后看看会发生什么):
您可以使用CountDownLatch
,这对于等待其他线程完成某些活动等任务非常方便(您可以将主线程中的Thread.sleep(…)
参数更改为12000L,然后查看发生了什么):
.run()
->.start()
。“仍然活动”是什么意思?什么是“活动”或“活动”是什么意思?可以通过getState()方法.run()
->.start()
获取线程状态。你还说“仍然活跃”是什么意思?“活着”或“活动”是什么意思?你可以通过GETStEATE()方法获得线程状态。我已经为你格式化了你的代码,但是这个答案也会从一些解释中受益匪浅。考虑一下改进你的答案。我已经为你格式化了你的代码,但是这个答案也会从一些解释中受益匪浅。考虑一下改进你的答案。