本帖最后由 赵太云 于 2013-7-16 20:31 编辑
为什么 wait()、notify()和notifyAll()方法只能在同步函数或同步代码块中使用?- public class Test{
- public static void main(String[] args){
- Resource resource = new Resource();
- Runnable r1 = new Input(resource);
- Runnable r2 = new Output(resource);
-
- new Thread(r1).start();
- new Thread(r2).start();
- }
- }
- class Resource{
- public String name;
- public String sex;
- public boolean flag=false;
- }
- class Input implements Runnable{
- private Resource resource;
- public Input(Resource resource){
- this.resource = resource;
- }
-
- public void run(){
- int x = 0;
- while (true){
- synchronized(resource){
- if (resource.flag){
- try{
- resource.wait();//这个为什么必须写在同步中?
- }catch(Exception e){
- }
- }
- if (0 == x){
- resource.name = "mike";
- resource.sex = "male";
- }else {
- resource.name = "丽丽";
- resource.sex = "女";
- }
- x = (x+1)%2;
- resource.flag = true;
- resource.notify();//这个为什么必须写在同步中?
- }
- }
- }
- }
- class Output implements Runnable {
- private Resource resource;
-
- public Output(Resource resource){
- this.resource = resource;
- }
-
- public void run(){
- while (true){
- synchronized(resource){
- if (!resource.flag){
- try{
- resource.wait();
- }catch(Exception e){
- }
- }
- System.out.println("name = " + resource.name + " sex = " + resource.sex);
- resource.flag = false;
- resource.notify();
- }
- }
- }
- }
复制代码 |