结果如下:
#1: 5
#2: 5
#1: 4
#3: 5
#1: 3
#2: 4
#3: 4
#2: 3
#1: 2
#4: 5
#1: 1
#2: 2
#5: 5
#3: 3
#5: 4
#2: 1
#4: 4
#5: 3
#3: 2
#5: 2
#4: 3
#5: 1
#3: 1
#4: 2
#4: 1
#2: 5
#1: 4
#3: 5
#1: 3
#2: 4
#3: 4
#2: 3
#1: 2
#4: 5
#1: 1
#2: 2
#5: 5
#3: 3
#5: 4
#2: 1
#4: 4
#5: 3
#3: 2
#5: 2
#4: 3
#5: 1
#3: 1
#4: 2
#4: 1
我们发现使用了yield对程序的输出结果并没有任何影响,原因何在了?原因还是线程的调度,线程的调度是以抢占式的方式进行,有时调度花去的时间太多,导致线程执行到yield时候线程对象可能已经被java虚拟机所回收了,因此在实际运用中yield用途还真的不大。
我在实际运用中使用最多的Thread方法是sleep,让线程休息一段时间,换句话说就是让线程暂停固定的时间。使用sleep方法的代码如下:
package cn.com.sxia;
public class SleepingThread extends Thread{
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread(){
super("" + ++threadCount);
start();
}
public String toString(){
return "#" + getName() + ": " + countDown;
}
public void run(){
while(true)
{ System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
for (int i = 0;i < 5;i++)
{
new SleepingThread();
}
}
}
public class SleepingThread extends Thread{
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread(){
super("" + ++threadCount);
start();
}
public String toString(){
return "#" + getName() + ": " + countDown;
}
public void run(){
while(true)
{ System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
for (int i = 0;i < 5;i++)
{
new SleepingThread();
}
}
}
结果如下:
#1: 5
#2: 5
#3: 5
#4: 5
#5: 5
#1: 4
#3: 4
#2: 4
#4: 4
#5: 4
#2: 3
#1: 3
#3: 3
#5: 3
#4: 3
#2: 2
#3: 2
#1: 2
#4: 2
#5: 2
#1: 1
#3: 1
#2: 1
#5: 1
#4: 1
#2: 5
#3: 5
#4: 5
#5: 5
#1: 4
#3: 4
#2: 4
#4: 4
#5: 4
#2: 3
#1: 3
#3: 3
#5: 3
#4: 3
#2: 2
#3: 2
#1: 2
#4: 2
#5: 2
#1: 1
#3: 1
#2: 1
#5: 1
#4: 1
我们发现调用sleep方法的地方要抛出一个异常InterruptedException,为什么会有这个异常呢?原因很简单,休眠的线程也有可能被终止,例如使用thread里的interrupt方法就会导致线程的终止,这种情况违反了sleep函数设计的初衷,因此会有导致在此抛出。我们回到上面join方法,join方法使用时候也会抛出InterruptedException,为什么呢?其实我们在调用join方法时候,被调用join方法的线程也是像调用sleep方法那样被休眠起来,它等待前一个线程执行结束的时候才能唤醒它,但是只要是休眠的线程同样也有可能被中断,这种结果也是方法不愿意接受的情况,因此会有InterruptedException异常的抛出。