开发者社区> 问答> 正文

有 wait就必须要有synchronized,不然会报错吗???报错

展开
收起
爱吃鱼的程序员 2020-06-14 17:24:10 756 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    这个代码没有 synchronized也没报错啊,怎吗做到滴???


    packagetank;
    importjava.awt.BorderLayout;
    importjava.awt.FlowLayout;
    importjava.awt.event.ActionEvent;
    importjava.awt.event.ActionListener;
     
    importjavax.swing.JButton;
    importjavax.swing.JFrame;
    importjavax.swing.JLabel;
    importjavax.swing.JPanel;
     
    publicclassTestAppextendsJFrameimplementsActionListener,Runnable{
      privateTestThreadthread=null;
     
      publicTestApp(){
     
        JPanelbuttons=newJPanel();
        FlowLayoutlayout=newFlowLayout(FlowLayout.CENTER);
        buttons.setLayout(layout);
        add(buttons,BorderLayout.NORTH);
     
        JButtonbtn=newJButton("pause");
        btn.addActionListener(this);
        buttons.add(btn);
     
        JLabellabel=newJLabel();
        add(label,BorderLayout.CENTER);
     
        setSize(800,600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        thread=newTestThread(label);
        thread.start();
      }
     
      publicstaticvoidmain(String[]args){
        newTestApp();
      }
     
      publicvoidactionPerformed(ActionEvente){
        JButtonbtn=(JButton)e.getSource();
        if("pause".equals(btn.getText())){
          btn.setText("start");
          thread.callWait();
        }else{
          btn.setText("pause");
          thread.call();
        }
      }
     
      publicvoidrun(){}
    }
     
    classTestThreadextendsThread{
      privatebooleanisWait=false;
      privateJLabellabe=null;
     
      publicTestThread(JLabellabe){
        this.labe=labe;
      }
     
      publicvoidrun(){
        intindex=0;
        while(true){
          try{
            if(isWait){
              wait();
            }
            labe.setText(""+(++index));
            sleep(500);
          }catch(Exceptione){
     
          }
        }
      }
     
      publicsynchronizedvoidcallWait(){
        isWait=true;
      }
     
      publicsynchronizedvoidcall(){
        isWait=false;
        notify();
      }
    }

     while(true){
    try{
                   if(isWait){
                       wait();
                   }
                   labe.setText(""+(++index));
                   sleep(500);
               }catch(Exceptione){

               }

    你把异常吃掉了

    2020-06-14 17:24:27
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
How Simplicity Will Unlock the True Potential of 立即下载
How Simplicity Will Unlock the 立即下载
低代码开发师(初级)实战教程 立即下载