毛嗲嗲 2013-09-10 02:08 采纳率: 100%
浏览 9062
已采纳

java如何停止当前正在运行的线程,新手求解答

最近想做一个无线数据监控服务端,用java做的,面板Jframe设置了一个Jpanel,我称这个为Jpanel 1 ,在Jpanel 1中我定义了一个多选JCheckbox,有四种监控方式可选:Bluetooth,Wifi,GPRS,Zigbee。还定义了一个JButton,分为开始ON,结束OFF,然后在JPanel 1中定义了JPanel 2,JPanel 2 中我定义了JScrollPane,scrollAndSetCursor用于实现滚动以及光标相关效果,程序运行的大致过程是这样的,我先选择监控方法,(方法是多选的,我想能够同步实现这几个方法),然后点击ON按钮就开始运行服务器程序了, 重点来了我现在的问题是 ,停止按钮OFF不知道怎么设置方法能够让程序停止当前的线程,我想实现的是点击OFF后,当前的监控方式运行全部停止,(就跟刚开始巡行这个程序一样,可以重新开始选择监控方式,在重新点击ON又可以重新运行),现在就是不知道怎么在jbArray[1](ON按钮的监控事件)中定义,感觉自己写的jbArray[0](ON按钮)也有问题。(我其实是想实现这四种方法可以同步运行,互不干扰,多线程运行)希望各位哥哥姐姐帮帮忙,帮我改一改jbArray[0](按钮的监听事件)以及实现jbArray[1](OFF结束当前监控方式线程事件),谢谢各位了,代码稍微有点长,我全贴上来了,辛苦各位了
package SystemTray;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.io.StreamConnection;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import BluetoothChatServer.*;
import GPRSChatServer.*;
import WifiChatServer.*;
import ZigbeeChatServer.*;

public class SystemTrayDemo extends JFrame {
protected JTextArea ta = new JTextArea(20,42);
protected Timer timer = new Timer();
protected boolean jbarry = false;
protected TrayIcon trayIcon = null;
protected SystemTrayDemo(){
this.setTitle("Data monitoring server");
TrayInit();
WinInit();

    //取得当前屏幕的宽度和高度
    int width=Toolkit.getDefaultToolkit().getScreenSize().width;
    int height=Toolkit.getDefaultToolkit().getScreenSize().height;
    //设置窗体大小
    this.setSize(610, 470);
    //设置窗体初始显示的位置
    this.setLocation((width-610)/2, (height-470)/2);
    this.setResizable(false);//设置窗体不可调整大小
    //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗体关闭方式,关闭窗体时同时结束程序

    final JPanel jp1 = new JPanel();
    jp1.setLayout(null);//不设置的话是无法设置jp2的大小。等同于窗口的大小。
    JPanel jp2=new JPanel();
    jp2.setBounds(110,20,480,390);
    //jp2.setBounds(new Rectangle(110,15,450,350));//设置jp2的左边距、上边距、长度、高度,在jp1没设置setLayout(null);是无效的
    //jp2.setBackground(Color.gray);//设置框体的背景色
    //jp2.setBorder(BorderFactory.createEtchedBorder(Color.black, Color.BLUE)); //设置框体的边框
    final JScrollPane jsp = new JScrollPane(ta);
    jp2.add(jsp,BorderLayout.CENTER);
    jp1.add(jp2);

    /*ta.setText("Start.....\n");
     TimerTask task = new TimerTask(){
       public void run(){
         ta.append("Time: " + (System.currentTimeMillis() / 1000) + "\n");
        scrollAndSetCursor();
       }
     };
     time.schedule(task, 0, 1000);*/            

    //super();
    //enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    //创建标签数组
    JLabel[] jlArray = {new JLabel("Switch"),new JLabel("Mode")};
    //创建复选框数组
    final JCheckBox[] jcbArray = {new JCheckBox("Bluetooth",true),new JCheckBox("Wifi"),new JCheckBox("GPRS"),
            new JCheckBox("Zigbee")};
    //创建按钮数组
    final JButton[] jbArray = {new JButton("ON"),new JButton("OFF")};

    //设置布局管理器
                for(int i=0;i<4;i++){
                //设置复选按钮的大小位置
                jcbArray[i].setBounds(10,185+i*30,80,30);   
                //将复选按钮添加到JPanel中
                jp1.add(jcbArray[i]);
                //设置标签与普通按钮的大小位置
                if(i>1){
                    continue;
                }       //continue后的语句不在执行。。
                jlArray[i].setBounds(30,20+i*140,80,30);
                jbArray[i].setBounds(10,50+i*45,80,30);
                //将标签与普通按钮添加到JPanel中
                jp1.add(jlArray[i]);
                jp1.add(jbArray[i]);
              }
            this.add(jp1);          
            //为普通按钮注册动作事件监听器。
            //开始按钮      **感觉这地方有问题,如何修改?????** 
            jbArray[0].addActionListener(new ActionListener(){  
                     public void actionPerformed(ActionEvent e) {

                         jbArray[0].setEnabled(jbarry);
                         int result= JOptionPane.showConfirmDialog(null,"Start monitoring program now?","Message",JOptionPane.YES_NO_OPTION);
                         if(result==0){
                            //是
                            StringBuffer temp0 = new StringBuffer();
                                for(int i = 0;i<4;i++){
                                        if(jcbArray[i].isSelected()){
                                            String tmpstr;
                                            tmpstr = jcbArray[i].getText()+" monitoring method ";
                                            ta.append(tmpstr + "\n");
                                            temp0.append(tmpstr);
                                        }                                   
                                    }
                                if(temp0.length()==0){
                                    JOptionPane.showMessageDialog(null,"The monitoring method can't be empty!","Message",JOptionPane.WARNING_MESSAGE);
                                    jbArray[0].setEnabled(!jbarry);
                                } 

                                //蓝牙线程
                                Thread Bluetooth = new Thread(){
                                    public void run() {
                                        if(jcbArray[0].isSelected()){ 
                                            new BluetoothRemoteServer();
                                        }
                                    }
                                };
                                //Bluetooth.setName("Bluetooth");
                                //String name0 = Bluetooth.getName();
                                //ta.append(name0+" start\n");
                                Bluetooth.start(); 
                                //Wifi线程
                                Thread Wifi = new Thread(){ 
                                    public void run() {
                                        if(jcbArray[1].isSelected()){ 
                                            new WifiRemoteServer();
                                        }
                                    }
                                };
                                //Wifi.setName("Wifi");
                               // String name1 = Wifi.getName();
                               // ta.append(name1+" start\n");
                                Wifi.start();
                                //GPRS线程
                                Thread GPRS = new Thread(){  
                                    public void run() {
                                        if(jcbArray[2].isSelected()){ 
                                            new GPRSRemoteServer();                         
                                        }
                                    }
                               };
                               //GPRS.setName("GPRS");
                               //String name2 = GPRS.getName();
                               //ta.append(name2+" start\n");
                               GPRS.start();
                               //Zigbee线程
                               Thread Zigbee = new Thread(){  
                                   public void run() {
                                       if(jcbArray[3].isSelected()){ 
                                            new ZigbeeRemoteServer();
                                       }
                                   }
                               };
                               //Zigbee.setName("Zigbee");
                               //String name3 = Zigbee.getName();
                               //ta.append(name3+" start\n");
                               Zigbee.start();     
                         }  
                        if(result==1){
                            //否   
                            jbArray[0].setEnabled(!jbarry);
                        }        
                     }
                  });
            //结束按钮    **如何实现点击jbArray[1]后能够停止前面jbArray[0]中选择的监控方式的线程?????** 
            jbArray[1].addActionListener(new ActionListener() {  
                 public void actionPerformed(ActionEvent e) {
                     int result= JOptionPane.showConfirmDialog(null,"End monitoring program now?","Message",JOptionPane.YES_NO_OPTION);
                     if(result==0){
                         //是
                         for(int i=0; i<jcbArray.length; i++){
                                jcbArray[i].setSelected(false);
                            }
                         ta.setText(null);
                         //后续功能完善
                         jbArray[0].setEnabled(!jbarry);

                     }                                       
                     if(result==1){
                         //否
                     }
                 }
            });   
}
//托盘的功能选项设置
public void TrayInit(){
    if(SystemTray.isSupported()){ //检查当前系统是否支持系统托盘
         SystemTray tray = SystemTray.getSystemTray();//获取表示桌面托盘区的 SystemTray 实例。
         URL imageUrl=SystemTrayDemo.class.getResource("java.png");
         ImageIcon icon = new ImageIcon(imageUrl);
       //Image image  = Toolkit.getDefaultToolkit().getImage("D:\\kissjava.gif");
         PopupMenu popupMenu = new PopupMenu(); //为托盘添加右键菜单
         MenuItem exitItem  = new MenuItem("Exit");                     
         //退出exitItem按钮
         exitItem.addActionListener(new  ActionListener(){
             public void actionPerformed(ActionEvent e){   
                 try{ 
                       System.exit(0);     
                   }catch(Exception  ex)   {   
                       ex.printStackTrace();   
                   }   
             }
         });                 
         popupMenu.add(exitItem); 
         //创建带指定图像、工具提示和弹出菜单的 TrayIcon
         trayIcon = new TrayIcon(icon.getImage(), "System is running",  popupMenu);   
         trayIcon.addMouseListener(new java.awt.event.MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e) {
               if(e.getClickCount()==2){                      
                   showIT(true);   
                }
            }     
         });
         try{   
              tray.add(trayIcon);  // 将 TrayIcon 添加到 SystemTray。 
         } catch   (AWTException   e)     {   
              System.err.println(e);   
         }
    }else{
         JOptionPane.showMessageDialog(null,"The operating system does not support tray","Message",JOptionPane.ERROR_MESSAGE);
    }

}

//窗体的菜单功能选项设置
public void WinInit(){      
    JMenuBar menubar = new JMenuBar();//为窗体添加菜单功能
    setJMenuBar(menubar);

    //开关option选项
    /*前端添加小图标
     * JMenu option = new JMenu("开关");
     * Icon startIcon = new ImageIcon("image/bluetooth.png");
       JMenuItem start = new JMenuItem("开始",startIcon);
       */

    //设置setting选项
    JMenu setting = new JMenu("Setting");
    JMenu language = new JMenu("Language");
    setting.add(language);
    JMenuItem language1 = new JMenuItem("中文");
    language.add(language1);
    JMenuItem language2 = new JMenuItem("English");
    language.addSeparator();
    language.add(language2);
    JMenu update = new JMenu("Update");
    setting.addSeparator();
    setting.add(update);
    JMenuItem update1 = new JMenuItem("Version update");
    update.add(update1);
    update1.addActionListener(new ActionListener() {  
         public void actionPerformed(ActionEvent e) {               
            JOptionPane.showMessageDialog(null,"please send the mail to zhouwenquan2012552061@Gmail.com","Message",JOptionPane.PLAIN_MESSAGE);
     } 
 });

    //关于help选项
    JMenu help = new JMenu("Help");
    JMenuItem about = new JMenuItem("About");
    help.add(about);
    //后续功能完善
    about.addActionListener(new ActionListener() {  
         public void actionPerformed(ActionEvent e) {               
            JOptionPane.showMessageDialog(null," Copyright @2013 popcorn\n All Right Reserved\n author popcorn\n version 1.0","Message",JOptionPane.PLAIN_MESSAGE);
     } 
 }); 

    menubar.add(setting);
    menubar.add(help); 
 }

/** 该方法用于实现滚动以及光标相关效果 */
public void scrollAndSetCursor(){
  // ta.requestFocus();
  ta.setSelectionStart(ta.getText().length());
}
public void showIT(boolean visable){
    if(this.isVisible() != visable)
        this.setVisible(visable);
}
public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            new SystemTrayDemo().setVisible(true);//设置窗体显示
        }
    });

}

}

  • 写回答

1条回答

  • Jobernowl 2013-09-10 04:22
    关注
    你这个只要停止方法即可停止线程
    比如 new GPRSRemoteServer();这句代码是在线程中执行的  你改成
    全局定义一个变量
    GPRSRemoteServer gs = null;
    
    
    然后线程中执行
    gs = new GPRSRemoteServer();
    
    
    停止按钮代码处则是
    if(null!=gs){
         gs.stop();
    }
    
    前提是你在该类GPRSRemoteServer中实现一个停止的方法   比如 stop 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致