gpt4 book ai didi

java - 监控和更新 Activity 进程数

转载 作者:行者123 更新时间:2023-12-01 13:40:25 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,该程序能够创建 .jar 和 .exe 进程并监视其中有多少进程处于 Activity 状态。我用来监视这些进程的方法是将它们添加到列表中并获取其大小,但是一旦窗口关闭,我就无法更新 Activity 进程的数量,我猜无法使用 waitFor() 方法因为我有多个进程,我应该在进程列表的迭代中使用 exitValue() 来检查它们是否已终止吗?

最佳答案

这里有一个例子来配合我的评论。相当困难,尽管如果您计划在生产环境中使用此代码,我会清理此代码。

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MainTest {

JLabel countLabel = new JLabel("");
Thread printer = null;

public static void main(String[] args) {
// passes in a directory

MainTest test = new MainTest();
}

public MainTest() {
JFrame frame = new JFrame("TestFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.setBounds(new Rectangle(200, 200, 200, 200));
JButton button = new JButton("Open Instances");
button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Thread t = new Thread(new Runnable() {

@Override
public void run() {
OpenStuff();
}

});
t.start();
}

});
countLabel.setSize(new Dimension(50, 50));

panel.add(countLabel);
panel.add(Box.createVerticalStrut(20));
panel.add(button);
printer = new Thread(new CountPrinter());
printer.start();
frame.add(panel);
frame.show();
}

private void OpenStuff() {
int count = 0;
ArrayList<Thread> threads = new ArrayList<Thread>();
while (count < 5) {
Thread t = new Thread(new OpenNotePadAndJoin());
t.start();
threads.add(t);
count++;
}

for (Thread t : threads) {
try {
t.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
printer.interrupt();
}

private static class SharedResource {
public static volatile int count = 0;
}

private class CountPrinter implements Runnable {

@Override
public void run() {
while (true) {
countLabel.setText(String.valueOf(SharedResource.count));
countLabel.getParent().repaint();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break;
}
}
}

}

private class OpenNotePadAndJoin implements Runnable {

@Override
public void run() {
ProcessBuilder pb = new ProcessBuilder("notepad");
try {

Process p = pb.start();
SharedResource.count++;
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
SharedResource.count--;
}

}

}
}

关于java - 监控和更新 Activity 进程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com