用线程将文件搜索器的停止
文件搜索器用线程来控制其实很简单:
先定义一个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");
???}
??});
这样就停止了。
?
?