问个线程的基本问题

allwearesaying 2008-10-11 09:46:24
class TestThread{

public static void main(String[] args){
final Foo f = new Foo();
Thread t= new Thread(){
public void run(){
f.dostuff();
}
};
Thread g = new Thread(){
public void run(){
f.dostuff();
}
};
t.start();
g.start();
}

}

class Foo
{
int x = 5;
public void dostuff(){
if(x<0){
try{
wait();
}
catch (InterruptedException w){
}
}
else{
System.out.println("x is "+ x++);
if (x>10){
notify();
}
}
}

}


在机器上跑了跑,居然得到x is 5
x is 6

不是没有锁的话就要抛出IllgalMonitorException异常的吗?

...全文
63 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZangXT 2008-10-11
  • 打赏
  • 举报
回复
你的
public void dostuff(){
if(x <0){
try{
wait();
}
catch (InterruptedException w){
}
}
else{
System.out.println("x is "+ x++);
if (x>10){
notify();
}
}
执行一次就结束了,
wait ,notify根本就不会执行,不知道你想测试什么?
andyheway 2008-10-11
  • 打赏
  • 举报
回复
up,学习了。
allwearesaying 2008-10-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ZangXT 的回复:]
你的
public void dostuff(){
if(x <0){
try{
wait();
}
catch (InterruptedException w){
}
}
else{
System.out.println("x is "+ x++);
if (x>10){
notify();
}
}
执行一次就结束了,
wait ,notify根本就不会执行,不知道你想测试什么?

[/Quote]

晕,才发现自己写错了。
对不住大家了。

62,616

社区成员

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

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