我想尝试一些想法,SwingWorker
因为我没有使用太多。相反,我遇到了一个问题,我不知道出了什么问题。
这是一个简短的SSCCE演示了这个问题(我知道这里的人喜欢 SSCCE):
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class SwingWorkerTest
{
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
@Override
public void run ()
{
new MySwingWorker (500).execute ();
new MySwingWorker (900).execute ();
new MySwingWorker (1200).execute ();
}
});
}
}
class MySwingWorker extends SwingWorker<Void, Void>
{
private int ms;
public MySwingWorker (int ms)
{
this.ms = ms;
}
@Override
protected Void doInBackground()
{
Thread t = Thread.currentThread ();
for (int i = 0; i < 50; i++)
{
try
{
Thread.sleep (ms);
}
catch (InterruptedException e)
{
e.printStackTrace ();
}
System.out.println ("I am thread with " + ms + " sleep in iteration " + i + ": " + t.getName () + " (" + t.getId () + ")");
}
return null;
}
}
所以我的程序应该创建 3 个 SwingWorker,它们在屏幕上打印一行,然后休眠指定的毫秒数,然后再次打印该行并再次休眠等。我SwingWorker
从 Swing 的线程中创建 s,否则它们甚至不会启动。
所以预期的输出是:
I am thread with 500 sleep in iteration 0: SwingWorker-pool-1-thread-1 (15)
I am thread with 900 sleep in iteration 0: SwingWorker-pool-1-thread-2 (16)
I am thread with 500 sleep in iteration 1: SwingWorker-pool-1-thread-1 (15)
I am thread with 1200 sleep in iteration 0: SwingWorker-pool-1-thread-3 (17)
I am thread with 500 sleep in iteration 2: SwingWorker-pool-1-thread-1 (15)
I am thread with 900 sleep in iteration 1: SwingWorker-pool-1-thread-2 (16)
I am thread with 500 sleep in iteration 3: SwingWorker-pool-1-thread-1 (15)
I am thread with 1200 sleep in iteration 1: SwingWorker-pool-1-thread-3 (17)
I am thread with 500 sleep in iteration 4: SwingWorker-pool-1-thread-1 (15)
I am thread with 900 sleep in iteration 2: SwingWorker-pool-1-thread-2 (16)
I am thread with 500 sleep in iteration 5: SwingWorker-pool-1-thread-1 (15)
I am thread with 500 sleep in iteration 6: SwingWorker-pool-1-thread-1 (15)
I am thread with 900 sleep in iteration 3: SwingWorker-pool-1-thread-2 (16)
I am thread with 1200 sleep in iteration 2: SwingWorker-pool-1-thread-3 (17)
I am thread with 500 sleep in iteration 7: SwingWorker-pool-1-thread-1 (15)
.............
依此类推,总共 150 行(3 个工作人员 x 50 次迭代)
相反,我得到的输出是:
I am thread with 500 sleep in iteration 0: SwingWorker-pool-1-thread-1 (15)
I am thread with 900 sleep in iteration 0: SwingWorker-pool-1-thread-2 (16)
I am thread with 500 sleep in iteration 1: SwingWorker-pool-1-thread-1 (15)
就是这样。就3行。之后程序退出。该try catch
块的任何地方都没有堆栈跟踪。
1)。睡眠时间为 1200 毫秒的工人在哪里?实际上,如果我用 1000 毫秒替换 1200 毫秒,那么这个工作人员也会打印 1 行……是的,只有一个。奇怪的...
2)。工人为什么停下来?(而且我没有得到 150 行的东西)
我在 Windows 7 64-bit 上使用 JRE 7 Update 11运行了这个程序。
PS:我很确定这里提到的错误在这个版本的 JRE 中得到了修复,因为我确实得到了 2 个不同的值(15 和 16)作为线程 ID 打印在控制台上。这是我怀疑的第一件事。