繁体   English   中英

提高线程速度[关闭]

[英]Increacing the speed of thread [closed]

每次调用线程后,它的速度都会提高(特别是-FirstCircleRepaintThread,SecoundCircleRepaintThread,LineRepaintThread)。 但是主线程的速度是正常的。 我已经读过这个问题,但是我线程的速度一直在增加。 GitHubDropbox PS 上的 JAR对不起,我的英语不好

问题是,每次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的状态。

看一下Swing中的并发性,并考虑使用SwingWorkerSwing Timer

您应该考虑维护尽可能少的后台进程,以保持性能并降低更改模型和交互的复杂性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM