一.线程的休眠
一种能控制线程行为的方法是调用sleep()方法,sleep()方法需要一个参数用于指定该线程休眠的时间,该时间以毫秒为单位,他通常在run()方法内的循环中被使用
sleep()方法的语法如下:
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
上述代码会使线程在2秒内不会进入就绪状态。由于sleep()方法的执行有可能抛出异常,因此放入try/catch块中。虽然使用了sleep()方法的线程在一段时间内会醒来,但是并不能保证它醒来后进入运行状态,只能保证它醒来后进入就绪状态
下面看一下实例:
package llxlqy;
public class llx {
private int count=10;
public llx(){
new Thread(new Runnable(){
public void run(){
while(true){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print(count+" ");
if(--count==0)return;
}
}
}).start();
};
public static void main(String[] args){
new llx();
}
}
效果如下:
二.线程的加入
如果当前某程序为多线程程序,假如存在一个线程A,现在需要插入线程B,并要求线程B先执行完毕,然后再继续执行线程A,此时可以使用Thread类中的join()方法来完成。这就好比此时读者正在看电视,突然有人上门收水费,读者必须付完水费后才能继续看电视。
当某个线程使用join()方法加入到另外一个线程时,另一个线程会等待该线程执行完毕后再继续执行。
下面看个使用join()方法的实例。
package llxlqy;
public class llx {
private int countA=5;
private int countB=5;
private Thread threadA;
private Thread threadB;
public llx(){
threadA=new Thread(new Runnable(){
public void run(){
try{
threadA.sleep(100);
threadB.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print("countA:");
while(true){
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print(countA+" ");
if(--countA==0)return;
}
}
});
threadA.start();
threadB=new Thread(new Runnable(){
public void run(){
System.out.print("countB:");
while(true){
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print(countB+" ");
if(--countB==0)return;
}
}
});
threadB.start();
};
public static void main(String[] args){
new llx();
}
}
效果如下:
三.线程的中断
如果线程是因为使用了sleep()或wait()方法进入了就绪状态,可以使用Thread类中interrupt()方法使线程离开run()方法,同时结束线程,但程序会抛出InterruptedException异常,用户可以在处理该异常时完成线程的中断业务处理,如终止while循环
package kop;
public class op {
private int countA=10;
public op(){
Thread threadA=new Thread(new Runnable(){
public void run(){
while(true){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.print("当前线程被中断");
break;
}
System.out.print(countA+" ");
if(--countA==0)return;
}
}
});
threadA.start();
threadA.interrupt();
};
public static void main(String[] args){
new op();
}
}
在本实例中,由于调用了interrupted()方法,所以抛出了InterruptedException异常。
四.线程的礼让
Thread类中提供了一种礼让方法,使用yield()方法表示,它只是给当前正处于运行状态下的线程一个提醒,告知它可以将资源礼让给其他线程,但这仅是一种暗示,没有任何一种机制保证当前线程会将资源礼让。
yield()方法使具有同样优先级的线程有进入可执行状态的机会,当当前线程放弃执行权时会再度回到就绪状态。对于支持多任务的操作系统来说,不需要调用yeild()方法,因为操作系统会为线程自动分配CPU时间片来执行