package wl; import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Frame; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.event.MouseEvent; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import javax.swing.border.Border; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class ProcessApp extends JFrame { static JFrame f = new JFrame("Process"); static JPopupMenu m_popupMenu;// 弹出式菜单、右键菜单 static JPanel panel = new JPanel(); static Object[][] cellData = { { "名称", "PID", "优先级", "状态", "用户名", "cpu", "内存", "描述" } }; static String[] columnNames = { "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8" }; static JTable table = new JTable(cellData, columnNames); static int focusedRowIndex = -1;// table mouse row number static List<processModel> processs = new ArrayList<processModel>(); static boolean isUpdate = true;// 是否更新:当鼠标左键按下后不再更新进程,当过去5秒后继续更新 private static ProcessApp p = new ProcessApp(); ProcessApp() {// init frame f.setVisible(true); f.setSize(1000, 800); f.setLayout(new BorderLayout()); } void initMenu() {// init menu JMenuBar menubar = new JMenuBar(); JMenu[] menus = new JMenu[] { new JMenu("文件"), new JMenu("选项"), new JMenu("查看") }; for (int i = 0; i < menus.length; i++) { menubar.add(menus[i]); } f.setJMenuBar(menubar); } void initToolBar() { JToolBar toolbar = new JToolBar(); JButton[] buttons = new JButton[] { new JButton("应用"), new JButton("进程"), new JButton("性能"), new JButton("联网"), new JButton("用户"), new JButton("性能") }; for (int i = 0; i < buttons.length; i++) { toolbar.add(buttons[i]); buttons[i].setFont(f.getFont().deriveFont(Font.PLAIN, 18f)); } toolbar.setBackground(Color.white); f.getContentPane().add(toolbar, BorderLayout.NORTH); } void initPanel() { panel.setBackground(Color.WHITE); f.getContentPane().add(panel, BorderLayout.CENTER); } void initTable() { // (1)名称,优先级,cpu,内存,磁盘,网络,GPU的使用情况,端口,用户名,状态,描述 table.setSize((int) (panel.getWidth() * 0.2), 40); table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); String[] headers = { "名称", "PID", "优先级", "状态", "用户名", "cpu", "内存", "描述" }; DefaultTableModel model = new DefaultTableModel(cellData, headers) { public boolean isCellEditable(int row, int column) { if(row==2){ return true;//返回true则表明单元格可编辑 } else{ return false; } } }; table = new JTable(model); panel.add(table); createPopupMenu();// 创建鼠标点击事件 } void setTable() { //System.out.println("setTable"); TableModel tableModel = table.getModel(); int rows = table.getRowCount();// get table rows //System.out.println(rows); while (rows > 1) {// if update not update finish,continue delete rows ((DefaultTableModel) tableModel).removeRow(0);// rowIndex是要删除的行序号 rows = table.getRowCount();// get table rows } // "名称","PID","优先级","状态","用户名","cpu","内存","描述" processs = process.Getprocess(); int i = 0; for (processModel p : processs) { String[] arr = new String[8]; arr[0] = p.getName(); arr[1] = p.getPID(); arr[2] = p.getPrio(); arr[3] = p.getState(); arr[4] = p.getUser(); arr[5] = Double.toString(p.getB_cpu()); arr[6] = Double.toString(p.getB_memory()); // arr[7] = p.getDescribe(); arr[7] = String.valueOf(i); i++; // 添加数据到表格 ((DefaultTableModel) tableModel).addRow(arr); } // 更新表格 table.invalidate(); table.setSize(panel.getWidth() - 20, panel.getHeight()); // JTable对象添加点击事件 table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { isUpdate = false; jTable1MouseClicked(evt); } }); } // 设置滚动条 void setScrollPane() { JScrollPane jsp; jsp = new JScrollPane(table); panel.add(jsp); } //table点击事件 private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { mouseRightButtonClick(evt); } //鼠标右键点击事件 private void mouseRightButtonClick(java.awt.event.MouseEvent evt) { // 判断是否为鼠标的BUTTON3按钮,BUTTON3为鼠标右键 if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) { // 通过点击位置找到点击为表格中的行 focusedRowIndex = table.rowAtPoint(evt.getPoint()); if (focusedRowIndex == -1) { //System.out.println(focusedRowIndex); } // 将表格所选项设为当前右键点击的行 table.setRowSelectionInterval(focusedRowIndex, focusedRowIndex); // 弹出菜单 m_popupMenu.show(table, evt.getX(), evt.getY()); } } public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { int selIndex = table.rowAtPoint(e.getPoint()); } } //创建鼠标点击事件 private static void createPopupMenu() { m_popupMenu = new JPopupMenu(); JMenuItem[] MenuItem = new JMenuItem[7]; for (int i = 0; i < MenuItem.length; i++) { MenuItem[i] = new JMenuItem(); } MenuItem[0].setText(" 结束进程 "); MenuItem[1].setText(" 结束进程树 "); MenuItem[2].setText(" 设置优先级 "); JMenu menu = new JMenu(" 资源值 "); JMenuItem m1 = new JMenuItem(); JMenuItem m2 = new JMenuItem(); m1.setText("值"); m2.setText("百分比"); menu.add(m1); menu.add(m2); MenuItem[3].setText(" 创建转储文件 "); MenuItem[4].setText(" 打开文件所在位置 "); MenuItem[5].setText(" 属性 "); m_popupMenu.add(MenuItem[0]); m_popupMenu.add(MenuItem[1]); m_popupMenu.add(MenuItem[2]); m_popupMenu.add(MenuItem[3]); m_popupMenu.add(MenuItem[4]); m_popupMenu.add(MenuItem[5]); m_popupMenu.add(MenuItem[6]); m_popupMenu.add(menu); MenuItem[0].addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // 该操作需要做的事 String pid = processs.get(focusedRowIndex - 1).getPID(); process.Killprocess(pid); p.setTable(); isUpdate = true;// 操作完成,继续更新 } }); MenuItem[1].addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // 该操作需要做的事 String pid = processs.get(focusedRowIndex - 1).getPID(); process.killProcessTree(pid); p.setTable(); isUpdate = true;// 操作完成,继续更新 } }); m1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // 该操作需要做的事 System.out.println("该操作需要做的事"); } }); m2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // 该操作需要做的事 System.out.println("该操作需要做的事"); } }); } public static void main(String[] args) { p.initMenu(); p.initToolBar(); p.initPanel(); p.initTable(); p.setTable(); p.setScrollPane(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Boolean result = false; int count = 0; while (!result) { try { Thread.sleep(10000); // 设置暂停的时间 5 秒 if (isUpdate == true) { count++; p.setTable(); System.out.println(sdf.format(new Date()) + "--循环执行第" + count + "次"); /* * if (count == 3) { result = true; break ; } */ } } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("finish"); } }
今天我实现了关闭进程数。原来我以为关闭进程树是指关闭该进程的父进程和子进程,父进程的其他子进程。但是百度之后发现只是关闭该进程的子进程,所示比较容易实现。
package wl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; public class process { //结束进程树 //结束进程树的特性就是在结束一个进程的同时结束由该进程直接或间接创建的子进程 //pstree -p pid 查看子进程 //返回子进程和父进程的id public static List<String> killProcessTree(String pid) { Runtime runtime = Runtime.getRuntime(); List<String> tasklist = new ArrayList<String>(); java.lang.Process process = null; List<processModel> processs=new ArrayList<processModel>(); int count = 0; // 统计进程数 try { /* * * 自适应执行查询进程列表命令 * */ Properties prop = System.getProperties(); // 获取操作系统名称 boolean is=false; String os = prop.getProperty("os.name"); if (os != null && os.toLowerCase().indexOf("linux") > -1) { // 1.适应与linux BufferedReader reader = null; //查询子进程 process = Runtime.getRuntime().exec("pstree -p "+pid); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); List<String> pids=new ArrayList<String>(); String line = null; while ((line = reader.readLine()) != null) { //System.out.println(line); int length=line.length()-1; String id=line.substring(length-4, length); pids.add(id); Killprocess(id); } } } catch (Exception e) { e.printStackTrace(); } return null; } //kill -9 [PID] 结束进程 public static void Killprocess(String pid) { Runtime runtime = Runtime.getRuntime(); List<String> tasklist = new ArrayList<String>(); java.lang.Process process = null; try { /* * * 自适应执行查询进程列表命令 * */ Properties prop = System.getProperties(); // 获取操作系统名称 boolean is=false; String os = prop.getProperty("os.name"); if (os != null && os.toLowerCase().indexOf("linux") > -1) { // 1.适应与linux BufferedReader reader = null; // 显示所有进程 //"名称","PID","优先级","状态","用户名","cpu","内存","磁盘","网络","描述" process = Runtime.getRuntime().exec("kill -9 "+pid); System.out.println("kill process:"+pid); } } catch (Exception e) { e.printStackTrace(); } } //get process infomation public static List<processModel> Getprocess() { Runtime runtime = Runtime.getRuntime(); List<String> tasklist = new ArrayList<String>(); java.lang.Process process = null; List<processModel> processs=new ArrayList<processModel>(); int count = 0; // 统计进程数 try { /* * * 自适应执行查询进程列表命令 * */ Properties prop = System.getProperties(); // 获取操作系统名称 boolean is=false; String os = prop.getProperty("os.name"); if (os != null && os.toLowerCase().indexOf("linux") > -1) { // 1.适应与linux BufferedReader reader = null; // 显示所有进程 //"名称","PID","优先级","状态","用户名","cpu","内存","磁盘","网络","描述" process = Runtime.getRuntime().exec("top -b -n 1"); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { if(line.startsWith(" PID")) { is=true; line=reader.readLine(); } if(is==true) { Pattern p = Pattern.compile("\s+"); Matcher m = p.matcher(line); line= m.replaceAll(","); String[] strs=line.split(","); processModel pro=new processModel(); pro.setPID(strs[1]); pro.setUser(strs[2]); pro.setPrio(strs[3]); pro.setMemory(Double.valueOf(strs[4])); pro.setState(strs[8]); pro.setB_cpu(Double.valueOf(strs[9])); pro.setB_memory(Double.valueOf(strs[10])); pro.setName(strs[12]); processs.add(pro); } } } } catch (Exception e) { e.printStackTrace(); } return processs; } public static void main(String[] args) throws Exception { //System.out.println(Getprocess());; //Killprocess("1239"); //installTool("iotop"); killProcessTree("2887"); } }
然后我想实现进程的排序功能。如果点击进程名,则按进程名的字母的先后顺序进程排序。我先写出了字符串排序的算法。
package wl; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 对字符串数组进行排序 * @author panjianghong * @since 2016/8/31 * */ public class StringSort { private static final Log _log = LogFactory.getLog(StringSort.class); /** * 对字符串数组进行排序 * @param keys * @return * */ public static String[] getUrlParam(String[] keys){ for (int i = 0; i < keys.length - 1; i++) { for (int j = 0; j < keys.length - i -1; j++) { String pre = keys[j]; String next = keys[j + 1]; if(isMoreThan(pre, next)){ String temp = pre; keys[j] = next; keys[j+1] = temp; } } } return keys; } /** * 比较两个字符串的大小,按字母的ASCII码比较 * @param pre * @param next * @return * */ private static boolean isMoreThan(String pre, String next){ if(null == pre || null == next || "".equals(pre) || "".equals(next)){ _log.error("字符串比较数据不能为空!"); return false; } char[] c_pre = pre.toCharArray(); char[] c_next = next.toCharArray(); int minSize = Math.min(c_pre.length, c_next.length); for (int i = 0; i < minSize; i++) { if((int)c_pre[i] > (int)c_next[i]){ return true; }else if((int)c_pre[i] < (int)c_next[i]){ return false; } } if(c_pre.length > c_next.length){ return true; } return false; } public static void main(String[] args) { ArrayList<processModel> list=new ArrayList<processModel>(); String[] strings = new String[list.size()]; list.toArray(strings); String[] keys = getUrlParam(strings); for (String key : keys) { System.out.println(key); } List list1 = java.util.Arrays.asList(strings); } }