每次调用线程后,它的速度都会增加(具体来说 - FirstCircleRepaintThread,SecoundCircleRepaintThread,LineRepaintThread)。但主线程的速度是正常的。我已经阅读了this个问题,但我的帖子的速度总是增加。 GitHub,JAR on Dropbox 附:抱歉我的英文不好
答案 0 :(得分:4)
问题是,每次unblock
你创建一个新的线程实例,但是你没有停止旧的实例,所以它们仍在运行,更新你的用户界面
public void block() {
setVisible(true);
// Create a bunch of new threads...
firstCircleThr = new FirstCircleRepaintThread();
firstCircleThr.setPriority(Thread.MAX_PRIORITY);
firstCircleThr.start();
secoundCircleThr = new SecoundCircleRepaintThread();
secoundCircleThr.setPriority(Thread.MAX_PRIORITY);
secoundCircleThr.start();
lineThr = new LineRepaintThread();
lineThr.setPriority(Thread.MAX_PRIORITY);
lineThr.start();
}
public void unblock(){
setVisible(false);
// Dereference the old ones, but they are still running...
firstCircleThr = null;
secoundCircleThr = null;
lineThr = null;
System.out.println("Yeah! OFF IT!");
}
例如......
public class FirstCircleRepaintThread extends Thread{
public static final long SPEED_OF_ROTATING = 25L;
@Override
public void run(){
//while(true){
MainCycle.frame.panel.startAngleFirst = 34;
int i = 0;
Random r = new Random();
// To infinity and beyond...
while(true){
你需要提供一些方法来阻止这些线程...而不需要调用stop
...
例如......
public class FirstCircleRepaintThread extends Thread{
private volatile boolean keepRunning = true;
public static final long SPEED_OF_ROTATING = 25L;
public void kull() {
keepRunning = false;
interrupt();
try {
join();
} catch (InterruptedException ex) {
}
}
@Override
public void run(){
//while(true){
MainCycle.frame.panel.startAngleFirst = 34;
int i = 0;
Random r = new Random();
while(keepRunning){
现在使用block
方法,您应该调用firstCircleThr.kull()
,这将在返回之前停止Thread
...
如果您使用调试器或在循环之间将帧保持可见,您可能已经看到了这一点......
现在,说了这么多,你违反了单线程规则Swing,从事件调度线程以外的每个线程更新UI的状态。
查看Concurrency in Swing并考虑使用SwingWorker
或Swing Timer
。
您应该考虑尽可能少地保留后台进程,以便保持性能并降低更改模型和交互的复杂性