日期:2014-05-19  浏览次数:20704 次

学习线程,请教线程输出停顿问题
我启动了10个线程, 每个线程输出i++的值,其中做了个判断,当i为5时当前线程sleep(2000),为什么后边的线程输出的时候也跟着停顿? PS:源码:

public class TestThread {

public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<10; i++){
TestRunnable b = new TestRunnable();
Thread t = new Thread(b);
t.start();
}
}

}

class TestRunnable implements Runnable{

@Override
public void run() {
try{
if(i == 5 ){
Thread.currentThread().sleep(2000);
}
System.out.println(i++);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int i=0;

}

------解决方案--------------------
逻辑不对.i=5的时候你让他sleep.也没放他继续哈
------解决方案--------------------
private static int i=0;

根本就是所有线程共享同一个i,当第一次System.out.println(i++);让i变成5以后,
当然后面的几个线程就都全部停顿2秒了,因为在停顿完毕之前没有线程去继续i++了。
------解决方案--------------------
探讨
知道为什么了 ,sleep和wait的区别,sleep没有释放对象锁的问题,所以5以后的线程都等待了2000,看来自己还要学啊……

------解决方案--------------------
Java code
public class TestThread {

public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<10; i++){
TestRunnable b = new TestRunnable();
Thread t = new Thread(b);
t.start();
}
}

}

class TestRunnable implements Runnable{

public void run() {
try{
if(i == 5 ){
System.out.println(Thread.currentThread().getName()+" will sleep 2 seconds....");
Thread.currentThread().sleep(2000);
System.out.println(Thread.currentThread().getName());
}
System.out.println(Thread.currentThread().getName() +" running :" + i++);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int i=0;

}

------解决方案--------------------
线程的顺序不是规范的 这是正常现象 就因为这种情况才会出现悲观锁