一道题答案看不懂

smwu 2003-05-08 09:16:45
class s extends Thread{int j=0;
public void run() {
try{Thread.sleep(5000);}
catch(Exception e){}
j=100;
}

public static void main(String args[])
{
s t1=new s();
t1.start();
System.out.println(t1.j);
}
}

what you have to do to ensure that 'j' will print 100

答案:You have to join the t1 to main

题目很明确 但是这个正确答案是什么意思?
...全文
42 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lishifeng 2003-05-20
  • 打赏
  • 举报
回复
不对,请注意join不是static method,所以调用时必须指明对象。而且其原形如下:
public final void join(long millis,int nanos) throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join() throws InterruptedException
因此需要写到try块里面。

class s extends Thread{int j=0;
public void run() {
try{Thread.sleep(5000);}
catch(Exception e){}
j=100;
}

public static void main(String args[])
{
s t1=new s();
t1.start();

//加在这里确保j输出100
try
{
t1.join(); //主线程等待t1的结束
}
catch(InterruptedException ie){}

System.out.println(t1.j);
}
}
weierjielang 2003-05-19
  • 打赏
  • 举报
回复
join(t1)
oldmaize 2003-05-09
  • 打赏
  • 举报
回复
我看了一下join的用法,有三种
public final synchronized void join(long millis)
public final synchronized void join(long millis, int nanos)
public final void join()
意思似乎是调用join的thread等待join入口参数设定的时间后,如果资源被释放了,该thread就使用,如果资源还没被释放,该thread就被killed,如果入口参数是0或者没有参数,thread就一直等到资源被释放为止,
是这样吗?
smwu 2003-05-09
  • 打赏
  • 举报
回复
哦 开始没有看懂 不过join的调用不能指明对象 也就是不能this.join(t1)
主线程怎么知道等待什么结束呢?
如果主线程创建了多个子线程又如何呢?
liuflei3139 2003-05-08
  • 打赏
  • 举报
回复
是这样的,你的程序启动后会有两个线程,一个是t1,另外一个是main。两个线程会同时运行,并行竞争cpu,所以无法保证j的值。如果你在t1.start();这句之后调用join(t1),系统就会保证:main线程会停下来,等待t1执行完然后再执行。这样就可以保证j的值为100。

不知道这样解释你是否明白,祝你愉快。

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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