注册 登录
编程论坛 JAVA论坛

一个运行就会把CPU100的程序

EdmundDantes 发布于 2017-02-28 16:48, 1286 次点击
package temple;
public class ThreadSafeTest implements Runnable {
    int num = 10; // 设置当前总票数
   
    public void run() {
        while (true) {
            if (num > 0) {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("tickets" + num--);
            }
        }
    }
   
    public static void main(String[] args) {
        ThreadSafeTest t = new ThreadSafeTest(); // 实例化类对象
        Thread tA = new Thread(t); // 以该类对象分别实例化4个线程
        Thread tB = new Thread(t);
        Thread tC = new Thread(t);
        Thread tD = new Thread(t);
        tA.start(); // 分别启动线程
        tB.start();
        tC.start();
        tD.start();
    }
}
这个代码,只要运行,CPU直接就100,什么毛病
5 回复
#2
EdmundDantes2017-02-28 16:48
在线等
#3
HolyOrder2017-03-01 17:41
死循环
#4
孤独与烈酒2017-03-06 11:01
以下是引用HolyOrder在2017-3-1 17:41:36的发言:

死循环

正解
#5
wuzhiwei2017-03-20 13:24
while (true) 出不去 , 1. 没必要加while (true)  2. 线程是不安全的   3.sleep 不应这么用
#6
九转星河2017-03-21 10:31
来学习一下~
1