- class Resource
- {
- public String name;
- public String sex;
- };
- class Input implements Runnable
- {
- boolean flag=true;
- private Resource r;
- Input(Resource r){
- this.r=r;
- }
- public void run(){
- synchronized(Input.class){
- while(true){
- if(flag){
- r.name="张三";
- r.sex="男";
- flag=false;
- }else{
- r.name="lili";
- r.sex="girl";
- flag=true;
- }
- }
- }
-
- }
- };
- class Output implements Runnable
- {
- private Resource r;
- Output(Resource r){
- this.r=r;
- }
- public void run(){
- synchronized(Input.class){
- while(true)
- System.out.println(r.name+"--"+r.sex);
- }
- }
-
- };
- class ResourceMain
- {
- public static void main(String[] args)
- {
- Object objs=new Object();
- Resource r=new Resource();
- Output out=new Output(r);
- Input in=new Input(r);
- Thread t1=new Thread(in);
- Thread t2=new Thread(out);
- t1.start();
- t2.start();
- }
- }
复制代码 如上代码,用Inout.class对象加锁同步后为什么成了死锁 ,程序不运行 ,不同步不加锁后却可以运行,这是为什么?
|
|