public class TextSynchronized implements Runnable{
int b=100;
public synchronized void A(){
b=150;
/*
try{
Thread.sleep(5000);
}catch(InterruptedException ae){
ae.printStackTrace();
}
*/
}
public synchronized void B(){
b=500;
}
public void run(){
A();
System.out.println(b);
}
public static void main(String [] args){
TextSynchronized t=new TextSynchronized();
Thread tt=new Thread(t);
tt.start();
t.B();
System.out.println(t.b);
try{
Thread.sleep(5000);
}catch(InterruptedException ae){
ae.printStackTrace();
}
System.out.println(t.b);
}
}
为什么总是先打印500呢
还有同步线程到底是怎么运行的?谢谢了
int b=100;
public synchronized void A(){
b=150;
/*
try{
Thread.sleep(5000);
}catch(InterruptedException ae){
ae.printStackTrace();
}
*/
}
public synchronized void B(){
b=500;
}
public void run(){
A();
System.out.println(b);
}
public static void main(String [] args){
TextSynchronized t=new TextSynchronized();
Thread tt=new Thread(t);
tt.start();
t.B();
System.out.println(t.b);
try{
Thread.sleep(5000);
}catch(InterruptedException ae){
ae.printStackTrace();
}
System.out.println(t.b);
}
}
为什么总是先打印500呢
还有同步线程到底是怎么运行的?谢谢了
楼主【temeisi518】截止到2008-07-19 03:13:58的历史汇总数据(不包括此帖):
发帖的总数量:2 发帖的总分数:40 每贴平均分数:20
回帖的总数量:1 得分贴总数量:0 回帖的得分率:0%
结贴的总数量:2 结贴的总分数:40
无满意结贴数:0 无满意结贴分:0
未结的帖子数:0 未结的总分数:0
结贴的百分比:100.00% 结分的百分比:100.00%
无满意结贴率:0.00 % 无满意结分率:0.00 %
敬礼!
这时候主线程和tt线程是同时运行的。虽然说是同时但是在一台计算机上还是有先有后的。
一般来说主线程的优先级会比tt的优先级高。所以就先执行了t.B()的的方法,现在t.B()的方法是主线程的。
然后主线程进入sleep,tt线程就开始工作了。这样就会执行run()从而启动了A()。
如果在tt.start()和t.B()之间加入很多其他的调用,就有肯先显示150了。