线程状态控制基本方法:
1、isAlive() ---- 判断线程是否还活着,即线程是否还未终止;
2、getPriority() ---- 获取线程的优先级数值;
3、setPriority() ---- 设置线程的优先级;
4、Thread.sleep() ----- 将当前线程睡眠指定毫秒数;
5、join(); ---- 调用某线程的该方法,将当前线程和该线程“合并”,即等待该线程结束,再恢复当前线程的运行;
6、yield() --- 让出CPU,当前线程进入就绪队列等待调度;
7、wait() --- 当前线程进入对象的wait pool
8、notify()/ notifyAll() ---- 唤醒对象的wait pool 中的一个/所有 等待线程;
例程:
1、package com.techpark.test.thread;
import java.util.Date;
public class TestInterrupt {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread myThread = new MyThread();
Thread t = new Thread( myThread );
t.start();
try {
t.sleep( 10000 );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// t.interrupt();
myThread.flag = false;
}
}
class MyThread implements Runnable {
boolean flag = true;
public void run() {
// TODO Auto-generated method stub
while( flag ){
System.out.println( new Date() );
try {
Thread.sleep( 1000 );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println( "Wow, Be interrupted!!!");
return;
}
}
}
}
例程2:
阅读(893) | 评论(0) | 转发(0) |