每次调用线程后,速度都会增加(特别是 - FirstCircleRepaintThread、SecoundCircleRepaintThread、LineRepaintThread)。但主线程速度正常。我读过this问题,但我的线程的速度总是在增加。 GitHub , JAR on Dropbox 附:抱歉我的英语不好
最佳答案
问题是,每次取消阻止
时,您都会创建线程的新实例,但不会停止旧线程,因此它们仍在运行,更新您的 UI
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
.
您应该考虑维护尽可能少的后台进程,以保持性能并降低更改模型和接口(interface)的复杂性
关于java - 提高线程速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22603095/