贴代码:public class b implements Runnable{
void f(){
synchronized (this){
try{
Thread.sleep(1000);
System.out.println("f()");
}catch(Exception e){e.printStackTrace();}
}
}
void g() throws Throwable{
System.out.println("start");
Thread t=new Thread(this);
t.setPriority(6);//当为7的时候结果和6不一样~~
t.start();
synchronized (this){Thread.sleep(2000);}
System.out.println(t.getPriority()+" "+Thread.currentThread().getPriority());
}
public void run(){
f();
}
public static void main(String[] args) throws Throwable {
new b().g();
}
}为啥当t.setPriority(6)时,锁是由主线程获得的?而当为7的时候锁却是由新建线程获得的。。呃。。就这里就迷糊了。。
void f(){
synchronized (this){
try{
Thread.sleep(1000);
System.out.println("f()");
}catch(Exception e){e.printStackTrace();}
}
}
void g() throws Throwable{
System.out.println("start");
Thread t=new Thread(this);
t.setPriority(6);//当为7的时候结果和6不一样~~
t.start();
synchronized (this){Thread.sleep(2000);}
System.out.println(t.getPriority()+" "+Thread.currentThread().getPriority());
}
public void run(){
f();
}
public static void main(String[] args) throws Throwable {
new b().g();
}
}为啥当t.setPriority(6)时,锁是由主线程获得的?而当为7的时候锁却是由新建线程获得的。。呃。。就这里就迷糊了。。
解决方案 »
- 关于mouselistener,请进来看下这段代码。。
- 怎么删除JTable容器下属所有的组件,不知道到组件名,但知道组件类型,如,删除JTable下所有的TextField组件
- 我是菜鸟:)求助关于数据库的操作
- 有哪位大侠知道Hashtable与Hashmap的不同吗?
- Applet 调用servlet的问题
- SSL的问题 急! 急! 急!
- VC可以查MSDN,JAVA如果有问题到哪里查,请各位指点一下。
- 两个对象怎样通信?
- 我没多少分了,我是初学者.请问编java用什么开发工具好?是vj吗?
- 虔诚的求教!
- SuperDemo构造函数重载
- 急急急!!!!明天要交员工管理系统,今天还没调试出来!!!在线等,急啊!
void f(){
try{
Thread.sleep(1000);
System.out.println("f()"+Thread.currentThread().getName());
}catch(Exception e){e.printStackTrace();}
}
void g() throws Throwable{
System.out.println("start");
Thread t=new Thread(this,"a");
t.setPriority(5);
Thread t2=new Thread(this,"b");
t2.setPriority(9);
Thread t3=new Thread(this,"c");
t3.setPriority(1);
Thread t4=new Thread(this,"d");
t4.setPriority(9);
Thread t5=new Thread(this,"e");
t5.setPriority(5);
t.start();t2.start();
t3.start();t4.start();t5.start();
synchronized (this){Thread.sleep(500);}
System.out.println("f()f");
}
synchronized public void run(){
f();
}
public static void main(String[] args) throws Throwable {
new b().g();
}
}
结果服从最高优先级的b先出现,紧接着是最低优先级的c,然后是e、a、f、d,这里的f因为是主线程所以比ea的优先级要高,可是比d的9要低。而且貌似我也没有遇到过非此顺序的输出,疑惑中~~~到底是不是概率性的事儿啊~~
而5和6几乎是同一个级别的,所以区别没怎么明显,而且start方法需要准备的时间,所以6的时候很容易被主线程抢了cpu
但是你将线程设置为7的时候,5和7就相差远了,所以,系统将会分配这个线程更多的时间和概率去争夺这个cpu