首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java线程:线程的部署-休眠

2013-07-16 
Java线程:线程的调度-休眠Java线程:线程的调度-休眠?Java线程调度是Java多线程的核心,只有良好的调度,才能

Java线程:线程的调度-休眠
Java线程:线程的调度-休眠?Java线程调度是Java多线程的核心,只有良好的调度,才能充分发挥系统的性能,提高程序的执行效率。?这里要明确的一点,不管程序员怎么编写调度,只能最大限度的影响线程执行的次序,而不能做到精准控制。?线程休眠的目的是使线程让出CPU的最简单的做法之一,线程休眠时候,会将CPU资源交给其他线程,以便能轮换执行,当休眠一定时间后,线程会苏醒,进入准备状态等待执行。?线程休眠的方法是Thread.sleep(long millis) 和Thread.sleep(long millis, int nanos) ,均为静态方法,那调用sleep休眠的哪个线程呢?简单说,哪个线程调用sleep,就休眠哪个线程。?/**?
* Java线程:线程的调度-休眠?
*?
* @author leizhimin 2009-11-4 9:02:40?
*/?
public?class?Test {?
????????public?static?void?main(String[] args) {?
????????????????Thread t1 =?new?MyThread1();?
????????????????Thread t2 =?new?Thread(new?MyRunnable());?
????????????????t1.start();?
????????????????t2.start();?
????????}?
}?

class?MyThread1?extends?Thread {?
????????public?void?run() {?
????????????????for?(int?i = 0; i < 3; i++) {?
????????????????????????System.out.println("线程1第"?+ i +?"次执行!");?
????????????????????????try?{?
????????????????????????????????Thread.sleep(50);?
????????????????????????}?catch?(InterruptedException e) {?
????????????????????????????????e.printStackTrace();?
????????????????????????}?
????????????????}?
????????}?
}?

class?MyRunnable?implements?Runnable {?
????????public?void?run() {?
????????????????for?(int?i = 0; i < 3; i++) {?
????????????????????????System.out.println("线程2第"?+ i +?"次执行!");?
????????????????????????try?{?
????????????????????????????????Thread.sleep(50);?
????????????????????????}?catch?(InterruptedException e) {?
????????????????????????????????e.printStackTrace();?
????????????????????????}?
????????????????}?
????????}?
}?线程2第0次执行!?
线程1第0次执行!?
线程1第1次执行!?
线程2第1次执行!?
线程1第2次执行!?
线程2第2次执行!?

Process finished with exit code 0?从上面的结果输出可以看出,无法精准保证线程执行次序。

本文出自 “熔 岩” 博客,请务必保留此出处http://lavasoft.blog.51cto.com/62575/221790

热点排行