黑马程序员技术交流社区
标题:
线程问题
[打印本页]
作者:
赵卓辉
时间:
2014-3-2 21:50
标题:
线程问题
请问,线程的优先级有哪些值?(如Thread.setPriority(a),----a的取值范围是多少?)
还有就是为什么在执行t2.join()的时候,线程1并没有等待线程2终止再执行,而是互相争夺CPU的执行权?
package com.zzh.bean;
class MyThreadDemo implements Runnable{
public void run(){
for(int i=0;i<5;i++)
{
System.out.println(Thread.currentThread().getName()+"----"+i);
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}}
}
public class ThreadTestDemo {
public static void main(String args[]) throws InterruptedException{
Thread t1=new Thread(new MyThreadDemo(),"Thread-1");
t1.setPriority(5);
t1.start();
Thread t2=new Thread(new MyThreadDemo(),"Thread—2");
t2.start();
t2.join();
}
}
<font color="red">/*
* 输出:
Thread-1
Thread—2
Thread-1
Thread—2
Thread-1
Thread—2
Thread-1
Thread—2
Thread-1
Thread—2
*/</font>
复制代码
作者:
Amorvos
时间:
2014-3-2 22:01
Java提供了10个优先级,但是这需要操作系统的支持,并不是所有的操作系统都有这么多优先级,一般main线程与其创建的主线程默认都是6。
设置优先级时尽量使用Java提供的静态常量,如:
MAX_PRIORITY
MIN_PRIORITY
NORM_PRIORITY
PS:
你要看现象的话,多试几次
作者:
榨菜
时间:
2014-3-2 22:05
你在join后面添加一句System.out.println("主线程"); 你会发现主线程停了。
作者:
榨菜
时间:
2014-3-2 22:18
二、为什么要用join()方法
主线程生成并起动了子线程,而子线程里要进行大量的耗时的运算(这里可以借鉴下线程的作用),当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join();方法了。
摘自:http://www.blogjava.net/jnbzwm/articles/330549.html
作者:
谭荣强
时间:
2014-3-2 22:32
(1)优先级有10(1-10)个,老毕说不建议用数字,要用MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY 即最大,最小,正常。
(2)你的join()方法理解错误。老毕原话:当A线程执行到了B线程的.join()方法时,A就会等待。等B线程执行完毕,A才会执行。你的代码中main()方法就是A线程。t1和t2没有执行与被执行的关系(读完t1,t1就玩命的执行它的线程,下面代码有main()执行,t2不执行t1才高兴呢). 所以t2就不满足A线程的条件。
我把你的代码加了个mian()方法。可以发现 t2.join() 是终止了main().
package com.zzh.bean;
class MyThreadDemo implements Runnable{
public void run(){
for(int i=0;i<5;i++)
{
System.out.println(Thread.currentThread().getName()+"----"+i);
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}}
}
public class ThreadTestDemo {
public static void main(String args[]) throws InterruptedException{
Thread t1=new Thread(new MyThreadDemo(),"Thread-1");
t1.setPriority(5);
t1.start();
Thread t2=new Thread(new MyThreadDemo(),"Thread—2");
t2.start();
t2.join();
for (int x= 0;x<5 ;x++ )
{
System.out.println("hahha");
}
}
}
/*
Thread—2----0
Thread-1----0
Thread—2----1
Thread-1----1
Thread-1----2
Thread—2----2
Thread-1----3
Thread—2----3
Thread-1----4
Thread—2----4
hahha
hahha
hahha
hahha
hahha
*/
作者:
多一点
时间:
2014-3-2 22:34
如果你没有给子线程指定优先级,运行时,谁抢到资源就谁先运行,
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2