贴代码: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的时候锁却是由新建线程获得的。。呃。。就这里就迷糊了。。
解决方案 »
- Map map = new HashMap();HashMap map = new HashMap();那种写法更好?
- 请教 我想打印出开方的那个符号, 即根号, 对应的unicode码是多少呢?
- 老紫竹和达人们请进,来评价一下我这套面试题,给些建议!~~谢谢
- 关于异常的处理谁帮个忙啊
- 大家帮我看看哪错了
- 求助关于流写入的问题
- 接口的方法不写参数行吗?
- jsp 连接问题,来啊
- 如何使JScrollPane出现滚动条
- 弱弱的问:JAVA提供的API函数是不是在WINDOWS里面和LINUX里面都能调用啊?
- 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