while(true);占用cpu不让出资源 :
详解在线程中while(true);与while(true)i++;的区别
先上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
public class MyThread { public static boolean bool=true;
public static synchronized void get(){ } public static void main(String[] args) { thread_1 a=new thread_1(); a.start(); thread_3 c=new thread_3(); c.start(); thread_2 b=new thread_2(); b.start(); System.out.println((int)'a'); } } class thread_1 extends Thread{ @Override public void run() { while (MyThread.bool){ } System.out.println("1end"); } } class thread_2 extends Thread{ @Override public void run() { for (int i = 0; i < 1000; i++) {
} MyThread.bool=false; } }
class thread_3 extends Thread{ @Override public void run() { System.out.println(74); int i=0; while (MyThread.bool){ i++; } System.out.println("3end"); } }
|
打住不要往下看我们先想一想执行结果是怎样的呢 是不是1end跟2end都会打印在控制台呢,
揭晓谜底