【发布时间】:2019-01-08 13:42:54
【问题描述】:
我有一个线程数组,我想启动其中的几个。关键是我想在 for 循环中停止线程。 在 for 循环中,我想检查所有线程是否正在运行,如果它们正在运行,我想被问到是否要停止它们(对话框是/否)。
问题是循环不会一直显示所有这三个启动线程的所有三个对话框。有时会出现 1 个对话框,有时会出现 3 个对话框等。
所以,我没有机会停止所有三个线程...
public class Main {
public static void main( String[] args )
{
Counter[] arrayOfThreads = new Counter[10];
for( int i = 0; i < arrayOfThreads.length; i++ )
{
arrayOfThreads[i] = new Counter( );
}
arrayOfThreads[3].start( );
arrayOfThreads[5].start( );
arrayOfThreads[2].start( );
for( int i = 0; i < arrayOfThreads.length; i++ )
{
if( arrayOfThreads[i].getState( ) == State.RUNNABLE )
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog( null, "Do you want to stop the theread: " + i, "Warning", dialogButton );
if( dialogResult == JOptionPane.YES_OPTION )
{
arrayOfThreads[i].stopProcessing( );
}
}
}
}
}
class Counter extends Thread
{
volatile boolean processing;
public void run( )
{
int i = 0;
processing = true;
while( processing )
{
System.out.println( " Number: " + i );
i++;
}
System.out.println( "finish" );
}
public void stopProcessing( )
{
processing = false;
}
}
编辑:
所以我想要的只是当我按下 EXIT 按钮关闭线程并在所有线程都停止时处理框架。我把第一堂课改得更清楚了。
public class Program extends Frame {
public static void main(String[] args) {
Counter[] arrayOfThreads = new Counter[10];
for (int i = 0; i < arrayOfThreads.length; i++) {
arrayOfThreads[i] = new Counter();
}
Program program = new Program(arrayOfThreads);
program.startThreeThreads(1, 4, 5);
}
private Counter[] arrayOfThreads;
private JButton stopThreads;
public Program(Counter[] arrayOfThreads) {
this.arrayOfThreads = arrayOfThreads;
stopThreads = new JButton("STOP THREADS");
closeThreadsWhenExitIsPressed();
setSize(300, 200);
setLayout(new FlowLayout());
add(stopThreads);
setVisible(true);
}
public void closeThreadsWhenExitIsPressed() {
stopThreads.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
stopRunningThreadsMethod();
dispose();
}
});
}
private void startThreeThreads(int first, int second, int third) {
for (int i = 0; i < arrayOfThreads.length; i++) {
if (i == first || i == second || i == third) {
arrayOfThreads[i].start();
continue;
}
}
}
public void stopRunningThreadsMethod() {
for (int i = 0; i < arrayOfThreads.length; i++) {
if (arrayOfThreads[i].isAlive()) {
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Do you want to stop the theread: " + i,
"Warning", dialogButton);
if (dialogResult == JOptionPane.YES_OPTION) {
arrayOfThreads[i].stopProcessing();
}
}
}
}
}
【问题讨论】:
-
请提供minimal reproducible example,这听起来不像是真实世界的例子。或者至少告诉我们您的真实用例。您想要创建和启动线程并在之后立即关闭它们似乎有点粗略
-
@Lino 将玩具呈现为minimal reproducible example 没有问题。事实上,这有时是最好的方法。
-
@Persixty 我认为它错了,我想鼓励 OP 解释他的逻辑的使用。正如第一条评论中提到的,我真的看不出这种设置的用途,因此我认为给出的示例不会很有用,尽管您的答案似乎已被接受,所以您已经理解了问题,只是我没有:)
标签: java multithreading