SCJP线程题目 求教

davis_rly 2010-04-05 03:50:42

public class Starter extends Thread
{
private int x = 2;
public static void main(String[] args) throws Exception
{
Starter a= new Starter();
a.makeItSo();
}
public Starter()
{
x = 5;
start();
}
public void makeItSo() throws Exception
{
System.out.println(Thread.currentThread().getName()+"------------->");
join();
x = x - 1;
System.out.println(x);
}
public void run()
{
System.out.println(Thread.currentThread().getName()+"------------->");
x *= 2;
}
} 答案是9 我认为答案不确定
我的理解是 如果makeitso的线程 和run的线程 都在可运行状态 但是JVM万一先挑选了makeitso的话 而且有join(),会等到该程序运行结束才执行run的代码 就是输出4了 有哪位高手可以请教一下? 谢谢
...全文
82 2 打赏 收藏 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
p2p81 2010-04-05
  • 打赏
  • 举报
回复
run()方法和makeItSo()方法的执行顺序是不确定的,但是x的值的计算顺序是确定的。因为join()方法暂停了main线程的执行.
wd9053 2010-04-05
  • 打赏
  • 举报
回复
注意join方法
public class Starter extends Thread
{
private int x = 2;
public static void main(String[] args) throws Exception
{
Starter a= new Starter();
a.makeItSo();
}
public Starter()
{
x = 5;
start();
}
public void makeItSo() throws Exception
{
System.out.println(Thread.currentThread().getName()+"------------->");
join();/////////////等待该线程终止。

x = x - 1;
System.out.println(x);
}
public void run()
{
System.out.println(Thread.currentThread().getName()+"------------->");
x *= 2;
}
}

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧