java - 这是我应该在 Java 中停止线程的方式吗?

标签 java multithreading

我的老师告诉我不要使用 stop() 而是在 Thread 类中使用这种方式:

public void pararHilo() { 
    stopHilo = true; 
}

public void run() {
    while (!stopHilo) 
        c++; 
} 

据我所知,当调用 pararHilo() 时,循环结束,因此它退出 run() 方法并且线程死亡。 问题是,我有一台相当不错的笔记本电脑,当使用此代码(在这里和在学校)进行测试时,我的机器变得非常滞后,我必须关闭 Eclipse...我错过了什么吗?

完整代码

public class EjemploHilo { 

    public static void main(String args[]) { 

        HiloPrioridad h1 = new HiloPrioridad(); 
        HiloPrioridad h2 = new HiloPrioridad();
        HiloPrioridad h3 = new HiloPrioridad();

        //el hilo con mas prioridad contara mas deprisa que los demas
        h1.setPriority(Thread.MAX_PRIORITY); 
        h2.setPriority(Thread.NORM_PRIORITY);
        h3.setPriority (Thread.MIN_PRIORITY); 

        h1.start(); h2.start(); h3.start();

        try { 
            Thread.sleep(2000); 
            } catch (Exception e) { } 

        h1.pararHilo(); 
        h2.pararHilo(); 
        h3.pararHilo(); 

        System.out.println("h1 (Prioridad Maxima): " + h1.getContador()); 
        System.out.println("h2 (Prioridad Normal): " + h2.getContador()); 
        System.out.println("h3 (Prioridad Minima): " + h3.getContador());

        } 

}

public class HiloPrioridad extends Thread { 

    private int c = 0; 
    private boolean stopHilo= false; 

    public int getContador() {
        return c; 
    }

    public void pararHilo() { 
        stopHilo = true; 
    }

    public void run() {
        while (!stopHilo) 
            c++; 
    } 

}

最佳答案

您的 while 循环应检查以下内容:

while (!Thread.currentThread().isInterrupted() && /* more work to do */) {
    // do more work
}

这样,客户端就可以调用Thread.interrupt(),将线程的中断状态设置为true

Note: When the interrupt method is called on a thread that blocks on a call such as sleep or wait, the blocking call is terminated by an InterruptedException, which should be handled:

try {
    while (!Thread.currentThread().isInterrupted() && /* more work to do */) {
        // do more work
        Thread.sleep(1000);
    }
} catch (InterruptedException e) {
    // thread was interrupted during sleep or wait
}

关于java - 这是我应该在 Java 中停止线程的方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641663/

相关文章:

java - Java中内存屏障的行为

java - Java volatile字段跨线程读写协调理解

java - 如何限制java菜单中的用户操作?

Java通用接口(interface)方法重载

java - 创建解析树以确定给定的 LL 语法的正确性

java - 如何从 Android 中的 BroadcastReceiver 调用 onPrepareOptionsMenu() ?

java - 错误 org.apache.kafka.common.utils.KafkaThread - 线程 'kafka-producer-network-thread 中未捕获的异常

iphone - 使用 webrequest 和 uialertview 在 MonoTouch 中线程化

c# - net.tcp 绑定(bind)上的线程不足 - TCP 错误代码 10061

Java 6 和 Java 8 之间的 Java BigDecimal.doubleValue