新手学线程的问题
public class Spy {public static void main(String[] args)
{
TreeHore th=new TreeHore();
SpyMan sm=new SpyMan(th);
ImformationMan im=new ImformationMan(th);
sm.start();
im.start();
}
}
class SpyMan extends Thread
{
TreeHore th;
SpyMan(TreeHore th)
{
this.th=th;
}
public void run()
{
for(int i=0;i<10;i++)
{
th.put(i);
System.out.println("spy put"+i+"imformation");
}
}
}
class ImformationMan extends Thread
{
TreeHore th;
ImformationMan(TreeHore th)
{
this.th=th;
}
public void run()
{
th.get();
}
}
class TreeHore
{
int value;
boolean b=false;
synchronized void put(int i)
{
if(b==false)
{
this.value=i;
b=true;
notify();
}
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
synchronized int get()
{
if(b==false)
{
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("Imformation get"+value+"imformation");
b=false;
notify();
return value;
}
}
以上程序主要想实现的功能是:间谍把情报放到树洞以后,等待,然后通知情报员,接着情报员去树洞取情报,情报员取了情报以后,等待,通知间谍接着放情报,循环10次,但是我这个执行了1次好象就死锁了还是什么,就出现
Imformation get0imformation
spy put0imformation
请高手帮忙看下,谢谢
搜索更多相关的解决方案:
线程
----------------解决方案--------------------------------------------------------
急啊,有人能解答下吗?
----------------解决方案--------------------------------------------------------
线程同步是指若干个线程都需要使用一个sycchronized修饰的方法
希望楼主再好好看一下线程同步的内容
public class Spy
{
public static void main(String[] args)
{
String smName="情报员",imName="间谍";
TreeHore th=new TreeHore(smName,imName);
Thread sm,im;
sm=new Thread(th);
im=new Thread(th);
sm.setName(smName);
im.setName(imName);
sm.start();
im.start();
}
}
class TreeHore implements Runnable
{
String smName,imName;
TreeHore(String s1,String s2)
{
smName=s1;
imName=s2;
}
public void run()
{
for(int i=0;i<10;i++)
putOrGet(i);
}
public synchronized void putOrGet(int i)
{
if(Thread.currentThread().getName().equals(smName))
{
System.out.println("spy put "+i+" imformation");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
else if(Thread.currentThread().getName().equals(imName))
{
System.out.println("Imformation get "+i+" imformation");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
这是我自己写的一段代码 不足之处请多多包涵
----------------解决方案--------------------------------------------------------
楼上的已经给你答了,你去网上sycchronized的相关资料,并且你还需要明白
wait():sleep():notify():Allnotity():
----------------解决方案--------------------------------------------------------
我就是想练习wait() notify()啊,你给的这段程序没用这2个方法
----------------解决方案--------------------------------------------------------