我有一个基于JFrame的Java GUI应用程序,它使用一个控制多个Java线程的Java类:
我试图控制从Control Class到
的任何线程到目前为止,Control Class可以创建一个线程并将其添加到ArrayList以跟踪所有创建的线程:
public class Control
{
ArrayList<myThread> threads;
int counter;
Control()
{
// do construction work..
}
int createThreadAndRun(String keyword)
{
// create an instance of myThread:
counter++;
myThread mythread = new myThread( keyword, counter);
mythread.runnable = true;
mythread.start();
// add it to ArrayList:
threads.add(mythread);
return counter;
}
boolean suspendByID( int id )
{
// loop over all threads in array:
for( myThread t : threads )
{
if( t.id == id && t.runnable == true )
{
t.runnable = false;
return true;
}
}
return false;
}
boolean unsuspendByID( int id )
{
for( myThread t : threads )
{
if( t.id == id && t.runnable == false )
{
synchronized(t)
{
t.runnable = true;
t.notify();
}
System.out.println("Thread "+id+" Unsuspended.");
return true;
}
}
return false;
}
boolean terminateByID( int id )
{
for( myThread t : threads )
{
if( t.id == id && t.terminated == false )
{
synchronized(t)
{
t.terminated = true;
if( !t.isAlive() )
t.notify();
}
System.out.println("Thread "+id+" terminated.");
return true;
}
}
return false;
}
void terminateAll()
{
for( myThread t : threads )
{
if( t.terminated == false )
{
synchronized(t)
{
t.terminated = true;
if( !t.isAlive() )
t.notify();
}
}
}
}
}
这是myThread类的逻辑:
class myThread extends Thread
{
protected volatile boolean runnable = false;
protected volatile boolean terminated = false;
Logger log;
myThread(String keyword, int id)
{
// constrcution work ..
log = new Logger();
}
@Override
public void run()
{
synchronized(this)
{
while(!terminated )
{
// do some work ...
this.wait(10000);
if(runnable == false)
{
System.out.println("Thread "+id+" is suspended.");
this.wait();
}
}
log.close();
System.out.println("Thread terminated.").
}
}
}
我的问题有两个:
1)我控制Control Class中的线程的方式是正确/最佳实践方式吗?
2)我想在我的GUI中覆盖formWindowClosing()
方法,以便它终止所有这样的线程:
private void formWindowClosing(java.awt.event.WindowEvent evt) {
// Terminate all threads and close all open files from Logger:
ret.terminateAll();
System.exit(0);
}
这也是最佳做法/正确方法吗? 目前,当JForm关闭时,myThread类末尾的语句:
log.close();
System.out.println("Thread terminated.").
根本没有执行。 我认为System.exit(0)应该等到所有线程完成运行/终止,但是如何?
答案 0 :(得分:0)
我找到了问题2的解决方案:
我在void terminateAll()方法中添加了一个join()语句:
void terminateAll()
{
for( myThread t : threads )
{
if( t.terminated == false )
{
synchronized(t)
{
t.terminated = true;
if( !t.isAlive() )
t.notify();
t.join() // blocks the execution until t finishes.
}
}
}
}
答案 1 :(得分:0)
考虑使用interrupt()
代替notify()
。如果您的线程工作负载涉及I / O,则中断它将使这些操作提前终止。