线程的基本控制

来源:互联网 发布:java linkedlist 反转 编辑:程序博客网 时间:2024/06/08 08:03

终止一个线程:

当一个线程结束运行并终止时,它就不能再运行了。可以用一个标志来指示run()方法,必须退出一个线程。

public class Runner implements Runnable {private boolean timeToQuit = false; //终止标志public void run() { while(! timeToQuit) { //当结束条件为假时运行... } }//停止运行的方法public void stopRunning() {timeToQuit = true;}}//控制线程类public class ControlThread {private Runnable r = new Runner();private Thread t = new Thread(r);public void startThread() {t.start();}public void stopThread() {r.stopRunning();}}

程的优先级

使用getPriority方法测定线程的当前优先级。使用setPriority方法设定线程的当前优先级。线程优先级是一个整数(110)。Thread类包含下列常数:

Thread.MIN_PRIORITY      1       (最低级别)

Thread.NORM_PRIORITY     5       (默认的级别)

Thread.MAX_PRIORITY      10      (最高级别)

延迟线程

sleep()方法是使线程停止一段时间的方法。在sleep时间间隔期满后,线程不一定立即恢复执行。这是因为在那个时刻,其它线程可能正在运行而且没有被调度为放弃执行,除非

(a)"醒来"的线程具有更高的优先级

(b)正在运行的线程因为其它原因而阻塞


原创粉丝点击