java多线程问题求解
public class TestThread extends Thread{
private static int threadCount = 0;
private int threadNum = ++threadCount;
private int i = 5;
public void run(){
while(true){
System.out.println("Thread " + threadNum + " = " + i);
try{
Thread.sleep(100);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
if(--i==0) return;
}
}
public static void main(String[] args){
for(int i=0; i<5; i++)
new TestThread().start();
}
}
输出 Thread 1 = 5
Thread 2 = 5
Thread 3 = 5
Thread 4 = 5
Thread 5 = 5
Thread 1 = 4
Thread 2 = 4
Thread 3 = 4
Thread 4 = 4
Thread 1 = 3
Thread 2 = 3
Thread 5 = 4
Thread 3 = 3
Thread 4 = 3
Thread 1 = 2
Thread 2 = 2
Thread 5 = 3
Thread 3 = 2
Thread 4 = 2
Thread 1 = 1
Thread 2 = 1
Thread 5 = 2
Thread 3 = 1
Thread 4 = 1
Thread 5 = 1
实际是Thread 2 = 5
Thread 1 = 5
Thread 4 = 5
Thread 3 = 5
Thread 5 = 5
Thread 1 = 4
Thread 2 = 4
Thread 4 = 4
Thread 3 = 4
Thread 5 = 4
Thread 1 = 3
Thread 2 = 3
Thread 4 = 3
Thread 3 = 3
Thread 5 = 3
Thread 2 = 2
Thread 1 = 2
Thread 5 = 2
Thread 4 = 2
Thread 3 = 2
Thread 1 = 1
Thread 2 = 1
Thread 4 = 1
Thread 5 = 1
Thread 3 = 1
------解决方案-------------------- 有关线程的问题没有那么绝对,这个得看谁能抢到cpu,至于谁抢到,这个有不确定性因素,那个线程抢到cpu和线程的创建线程的创建先后顺序没有必然联系,线程1先创建,线程二后创建,cpu执行速度很快,可以看做是同时创建的,但是二抢到了cpu,一没有抢到,因此二在一的前面执行,你每次执行打印结果应该都有变化
------解决方案-------------------- 引用: Quote: 引用:
第一个线程执行时sleep下来不应该是第二个线程吗,为什么不是?在for循环里面创建线程的时候不是先建线程一 然后才是线程二吗,还有
不是先建的线程执行后,才会返回到for循环里面再创建下一个线程吗
这样和你说吧。每个线程就像皇帝的妃子,你创建了5个线程就有五个妃子,而cpu就是皇帝。虽然这几个妃子都进宫了,都可以得到皇帝(cpu)的宠幸。可是他毕竟是皇帝,他不管你们妃子谁先进来的。他会从妃子中选自己喜欢的。可是你的每个线程都在执行的时候,都sleep()了,这个就好比,皇帝本来想宠幸这个妃子,可以刚到寝宫,妃子说,皇帝我今天有点累了,先让我休息100分钟吧,皇帝说,好吧~~不勉强你,我去宠幸其他妃子了,等你休息够了,我再回来,就是这样一个过程。希望对你有帮助。