解决这个问题,要看这个进程是java程序自定义的进程,还是操作系统的进程,操作系统的进程,又可以分为windows进程和Linux进程
一、针对操作系统的进程:
1,首先java用户,要具有操作进程的权限
2. 针对windows操作系统的进程,比如QQ进程:
String command = "taskkill /f /im QQ.exe"Runtime.getRuntime().exec(command)
其中:taskkill 是命令名称,/f /im 是参数,QQ.exe是进程的可执行文件。
3.针对Linux操作系统
String command = "kill /f /im QQ.exe"Runtime.getRuntime().exec(command)
二、在Java程序中自定义的进程
思路:在线程中设置一个标志变量,当这个变量的值在外界被改变的时候,有机会结束运行的线程
public class T {public static void main(String[] args) {
// 启动线程
MyThread thread = new MyThread()
new Thread(thread).start()
// 你的其它的工作,此时线程在运行中
// 你不想让线程干活了,停掉它
// 注意,这只是一个标志,具体线程何时停,并不能精确控制
thread.allDone = true
}
}
class MyThread implements Runnable {
boolean volatile allDone = false
public void run() {
// 每次循环都检测标志
// 如果设置停止标志时已经在循环里
// 则最长需要等待一个循环的时间才能终止
while (!allDone) {
// 循环里的工作
}
}
}
import java.util.Scannerpublic class test {
public static void main(String[] args) {
for (int i = 0 i < 10 i++) {
System.out.println(i)
}
do{
System.out.println("输入y或者Y 再将结果输出一遍;输入n或者N结束程序")
Scanner shuru = new Scanner(System.in)
String s = shuru.next()
if(s.trim().equalsIgnoreCase("Y")){
for (int i = 0 i < 10 i++) {
System.out.println(i)
}
}else if(s.trim().equalsIgnoreCase("N")){
break
}
}while(true)
}
}
Runtime.getRuntime().exec("这个地方 直接写命令")例如:
Runtime.getRuntime().exec("shutdown -s -t 10")