用線程將文件搜索器的停止

文件搜索器用線程來控制其實很簡單:

先定義一個button--begin,添加一個監聽器匿名內部類

 JButton btnStart = new JButton("立即搜索");
  this.add(btnStart);

  /**
   * 匿名內部類
   */
  btnStart.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {

    cf.start();
    
   }

  });

在調用線程時先重寫run方法,

public void run() {

  System.out.println("88888888888888");

  while (running) {
   fileName = txtFile.getText();
   // 得到用戶要查找的盤符
   String pathName = (String) cbItem.getSelectedItem();
   System.out
     .println("要查找的文件名是:" + fileName + "\t要查找的磁盤是:" + pathName);

   // 調用查找的方法
   int count = queryFile(pathName);

   txtMessage.append("總計查找的文件數:" + count + "\n查找到的文件有:" + this.count);

  }

 }

也就是當我們點擊開始時線程被啓動,我們開始查找文件。

最讓人糾結的是停止線程的方法:

人們一般都習慣於將while語句中的true變爲false,其實這樣就麻煩了,我的思想是當我們點擊停止時整個線程就全部停止,跳出循環:

就用一個語句:

 */
  JButton btnStop = new JButton("停止搜索");
  btnStop.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {

    cf.suspend();
   
    System.out.println("rrrrrrrrrrrrrrrr");
   }
  });

這樣就停止了。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章