黑马程序员技术交流社区
标题:
线程问题
[打印本页]
作者:
赵卓辉
时间:
2014-3-2 16:09
标题:
线程问题
请问,线程的优先级有哪些值?(如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>
复制代码
作者:
血剑无痕
时间:
2014-4-3 20:38
看看底层源码再来解析“线程的优先级有哪些值”
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
Thread t1=new Thread("Thread-1");
t1.setPriority(5);
System.out.println(t1.MAX_PRIORITY+":::"+t1.MIN_PRIORITY);
结果打印:;10:::1所以有限级的限定有几个值应该懂了吧。
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
看看着部分join的代码在看看
void join()
等待该线程终止。
void join(long millis)
等待该线程终止的时间最长为 millis 毫秒。
void join(long millis, int nanos)
等待该线程终止的时间最长为 millis 毫秒 + nanos 纳秒。
通过底层源码和api文档我们了解到该方法是线程等待终止的懂了吗?你所说的可能是多核cpu出现的问题这是对于单cpu编程。具体问题可以参见多核cpu的编程内容
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2