同学你好,下面是我修改你的代码后的结果,里面有注释解释一些地方进行的改变- class User
- {
- private String name;
- private float pay;
- protected void setName(String name){
- this.name=name;
- }
- protected String getName(){
- return this.name;
- }
- protected void setPay(float pay){
- this.pay=pay;
- }
- protected float getPay(){
- return this.pay;
- }
- public boolean flag=false;
- }
- class AOper implements Runnable
- {
- private User user;
- AOper(User user){
- this.user=user;
- }
- public void run(){
- int i=0; //这里应该把标记放在while(true)的外面,否则,i每次又都会等于0,else就执行不到
- while(true)
- {
-
- synchronized(user){
- if(user.flag)
- try{user.wait();}catch(Exception e){}
- if(i==0){
- user.setName("zk");
- user.setPay(9000f);
- }else{
- user.setName("lii");
- user.setPay(12000f);
- }
- i=(i+1)%2;
- user.flag=true;
- user.notify();
- }
- }
- }
- }
- class BOper implements Runnable
- {
- private User user;
- BOper(User user){
- this.user=user;
- }
- public void run(){
- synchronized(user){
- while(true){ //这里也需要使用while(true),之前是因为它只执行了一次
- if(!user.flag)
- try{user.wait();}catch(Exception e){}
- System.out.println("name:"+user.getName()+"--pay:"+user.getPay());
- user.flag=false;
- user.notify();
- }
- }
- }
- }
- class UserTest
- {
- public static void main(String[] args)
- {
- User user=new User();
- AOper a=new AOper(user);
- BOper b=new BOper(user);
- Thread t1=new Thread(a);
- Thread t2=new Thread(b);
- t1.start();
- t2.start();
- }
- } // 执行程序后一直等待.....成了死锁,怎么改呢?
复制代码 |