主要是完成一个从被监控端收集CPU信息,然后通过socket发送到监控端的过程。被监控端的窗口上有两个按钮,开始和暂停。按下开始开启线程,每秒提取CPU信息并发送,按停止希望能关闭线程。但我线程没学好,开启后锁死在那了,其他按钮按不动了,求帮助,这里怎么搞。部分代码如下:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
p = true;
/*s();*/
while(p){
try{Thread.sleep(2000);}
catch(Exception e){}
start();
}
}
public void start(){
  //建立联网线程
   new Thread(new Runnable(){
   public void run() {
    try {
     s=new Socket("127.0.0.1",5555);
     //写
   Sigar sigar = new Sigar();
   Mem mem = sigar.getMem();
   CpuPerc cpuCerc = sigar.getCpuPerc();
   q = cpuCerc.getCombined()*100 + "%;" + cpuCerc.getUser()*100 + "%;"
   +cpuCerc.getSys()*100+"%";
          byte[] b = q.getBytes();
   os=s.getOutputStream(); 
   os.write(b);
    os.flush();
   //读内容
   Thread.sleep(1000);
     /*is=s.getInputStream();
     int len=is.available();
     System.out.println("len:"+len);
     byte[] bytes=new byte[len];
     is.read(bytes);
     String resut=new String(bytes);
     System.out.println("resut:"+resut);*/
     //TODO 这里通过返回结果处理
       
    } catch (UnknownHostException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    } catch (SigarException e) {
 e.printStackTrace();
} catch (InterruptedException e) {
 e.printStackTrace();
}finally{
    }
   }    
  }).start();
 } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//p = false;
//Thread.interrupted();
        这里不会写了,写了这个按钮也按不动
}

解决方案 »

  1.   

    /*
     * Client1.java
     *
     * Created on __DATE__, __TIME__
     */package demo;/**
     *
     * @author  __USER__
     */
    public class Client1 extends javax.swing.JFrame {
    static boolean p = true;
    /** Creates new form Client1 */
    public Client1() {
    initComponents();
    } /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    //GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() { jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("\u5f00\u59cb");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    }); jButton2.setText("\u6682\u505c");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
    getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(
    javax.swing.GroupLayout.Alignment.LEADING).addGroup(
    layout.createSequentialGroup().addGap(48, 48, 48).addComponent(
    jButton1).addPreferredGap(
    javax.swing.LayoutStyle.ComponentPlacement.RELATED,
    161, Short.MAX_VALUE).addComponent(jButton2).addGap(77,
    77, 77)));
    layout.setVerticalGroup(layout.createParallelGroup(
    javax.swing.GroupLayout.Alignment.LEADING).addGroup(
    layout.createSequentialGroup().addGap(91, 91, 91).addGroup(
    layout.createParallelGroup(
    javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jButton1).addComponent(jButton2))
    .addContainerGap(184, Short.MAX_VALUE))); pack();
    }// </editor-fold>
    //GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    p = false;
    } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    p = true;
    new MyThread();
    new MyThread().start();
    } /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Client1().setVisible(true);
    }
    });
    }
    public boolean getP(){
    return p;
    }
    //GEN-BEGIN:variables
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration//GEN-END:variables}
      

  2.   

    package demo;import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.sql.Timestamp;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.StringTokenizer;public class Server {
     public static final int SERVERPORT=5555;
     public static final String USERNAME="wangzhirong";
     public static final String PASSWORD="123456";
     public static final String ISACK="ACK";
     public static final String ISNAK="NAK!";
    // Selector selector;//选择器
    // SelectionKey key;//key。 一个key代表一个Selector 在NIO通道上的注册,类似主键;
    //      //取得这个Key后就可以对Selector在通道上进行操作
     private ByteBuffer echoBuffer = ByteBuffer.allocate( 1024 );// 通道数据缓冲区
     public Server(){
     }
     public static void main(String[] args) throws IOException {
      Server ns=new Server();
      ns.BuildNioServer();
     }
     public void BuildNioServer() throws IOException{
      /////////////////////////////////////////////////////////
      ///////先对服务端的ServerSocket进行注册,注册到Selector ////
      /////////////////////////////////////////////////////////
      ServerSocketChannel ssc = ServerSocketChannel.open();//新建NIO通道
      ssc.configureBlocking( false );//使通道为非阻塞
      ServerSocket ss = ssc.socket();//创建基于NIO通道的socket连接
      //新建socket通道的端口
      ss.bind(new InetSocketAddress("127.0.0.1",SERVERPORT));
      Selector selector=Selector.open();//获取一个选择器
      //将NIO通道选绑定到择器,当然绑定后分配的主键为skey
      SelectionKey skey = ssc.register( selector, SelectionKey.OP_ACCEPT );
      ////////////////////////////////////////////////////////////////////
      ////   接收客户端的连接Socket,并将此Socket也接连注册到Selector   ////
      ///////////////////////////////////////////////////////////////////
      while(true){
       int num = selector.select();//获取通道内是否有选择器的关心事件
       if(num<1){continue; }
       Set selectedKeys = selector.selectedKeys();//获取通道内关心事件的集合
       Iterator it = selectedKeys.iterator();
       while (it.hasNext()) {//遍历每个事件
        try{
         SelectionKey key = (SelectionKey)it.next();
         //有一个新联接接入事件,服务端事件
         if ((key.readyOps() & SelectionKey.OP_ACCEPT)
                   == SelectionKey.OP_ACCEPT) {
                  // 接收这个新连接
                  ServerSocketChannel serverChanel = (ServerSocketChannel)key.channel();
                  //从serverSocketChannel中创建出与客户端的连接socketChannel
                  SocketChannel sc = serverChanel.accept();
                  sc.configureBlocking( false );
                  // Add the new connection to the selector
                  // 把新连接注册到选择器
                  SelectionKey newKey = sc.register( selector, 
                    SelectionKey.OP_READ );
                  it.remove();
                  System.out.println( "Got connection from "+sc );
         }else
         //读客户端数据的事件,此时有客户端发数据过来,客户端事件 
         if((key.readyOps() & SelectionKey.OP_READ)
                   == SelectionKey.OP_READ){
                  // 读取数据
                  SocketChannel sc = (SocketChannel)key.channel();
                  int bytesEchoed = 0;
                  while((bytesEchoed = sc.read(echoBuffer))> 0){
                   /*System.out.println("bytesEchoed:"+bytesEchoed);*/
                  }
                  echoBuffer.flip();
                  /*System.out.println("limet:"+echoBuffer.limit());*/
                  byte [] content = new byte[echoBuffer.limit()]; 
                  echoBuffer.get(content);
                  String result=new String(content);
                  /*doPost(result,sc);*/
                  System.out.println(result);
                  String[] array = result.split(";"); 
                  System.out.println("#总使用率: " + array[0]); 
                  System.out.println("#用户使用率(user): " + array[1]); 
                  System.out.println("#系统使用率(sys): " + array[2]); 
         }   
        }catch(Exception e){}
       }
      }
     }
    }
      

  3.   

    package demo;import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;import org.hyperic.sigar.CpuPerc;
    import org.hyperic.sigar.Mem;
    import org.hyperic.sigar.Sigar;
    import org.hyperic.sigar.SigarException;public class MyThread extends Thread{
    boolean p = true;
    public void run(){
    OutputStream os;
    Socket s;
    InputStream is;
    String a;
    while(p){
        try {
    s=new Socket("127.0.0.1",5555);
    Sigar sigar = new Sigar();
    Mem mem = sigar.getMem();
    CpuPerc cpuCerc = sigar.getCpuPerc();
    a = cpuCerc.getCombined()*100 + "%;" + cpuCerc.getUser()*100 + "%;"
    +cpuCerc.getSys()*100+"%";
    byte[] b = a.getBytes();
    os=s.getOutputStream(); 
    os.write(b);
    os.flush();
    Client1 c= new Client1();
    p = c.getP();
    System.out.println(p);
    //读内容
    Thread.sleep(3000);
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (SigarException e) {
    e.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }