java - 提高线程速度

标签 java multithreading swing

每次调用线程后,速度都会增加(特别是 - 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并考虑使用 SwingWorkerSwing Timer .

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

关于java - 提高线程速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22603095/

相关文章:

java - 如果 Spring MVC 中包含特定的 thymeleaf 段,如何从数据库加载数据

java - 计算 "Flower Objects"数组中出现的次数

java - Tomcat (7, 8) 启动失败,出现 java.lang.ClassNotFoundException : org. apache.tomcat.util.res.StringManager

java - 如何在没有队列的情况下实现此并发结构?

java - 多个 GUI 之间的连接

java - 无法加载 sigar-amd64-winnt : java. lang.NullPointerException

c - 在 C 中使用 pthread?

Java多线程 vector 加法

java - 用鼠标旋转矩形不一致

java - JFrame 上的 MouseListener