本帖最后由 ying 于 2013-1-8 13:14 编辑
- <P>class Res
- {
- String name;</P>
- <P> String sex;</P>
- <P> boolean flag = false;</P>
- <P>}
- /*
- Input线程负责
- 向资源对象中存放数据
- */
- class Input implements Runnable
- {
- private Res r ;
- Object obj = new Object();
- Input(Res r)
- {
- this.r = r;
- }</P>
- <P> public void run()
- {
- int x = 0;
- while(true)
- {
- synchronized(r)
- {
- if(r.flag)
- try{r.wait();}catch(Exception e){};
- if(x == 0)
- {
- r.name = "mike";
- r.sex = "male";
- x = 1;
- }else{
- r.name = "丽丽";
- r.sex = "女女女女女";
- x = 0;
- }
- r.flag = true ;
- notify();
- }
- }
- }
- }
- /*
- Output此线程负责
- 从资源对象中取出数据并打印
- */
- class Output implements Runnable
- {
- private Res r ;</P>
- <P> Output(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- while(true)
- {
- synchronized(r)
- {
- if(!r.flag)
- try{r.wait();}catch(Exception e){};
- System.out.println(r.name + "..." + r.sex);
- r.flag = false;
- notify();
- }
- }
- }
-
- }
- /*
- 演示线程同步及线程通信
- */
- class InputOutputDemo
- {
- public static void main(String[] args)
- {
- //创建资源对象 Input和Output线程共享此资源
- Res r = new Res();
-
- Input in = new Input(r);</P>
- <P> Output out = new Output(r);</P>
- <P> //创建线程t1和t2 并分别启动
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);</P>
- <P> t1.start();
- t2.start();</P>
- <P>
- }
- }</P>
复制代码 本人对线程中的wait()和notify()方法不太理解,我的这段代码可以编译但不可以执行,出现异常如下!谁能帮忙看看指点一下!
|
|