成都网站建设设计

将想法与焦点和您一起共享

模拟进程代码java,进程调度模拟程序

用java实现一个模拟操作系统内核运行的程序。(1)进程控制:其中包括进程创建与撤销

在编写Java程序时,有时候需要在Java程序中执行另外一个程序。

创新互联公司主要从事网站建设、做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务凉城,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

1、启动程序Java提供了两种方法用来启动其它程序:

(1)使用Runtime的exec()方法

(2)使用ProcessBuilder的start()方法

不管在哪种操作系统下,程序具有基本类似的一些属性。一个程序启动后就程序操作系统的一个进程,进程在执行的时候有自己的环境变量、有自己的工作目录。Runtime和ProcessBuilder提供了不同的方式来启动程序,设置启动参数、环境变量和工作目录。

能够在Java中执行的外部程序,必须是一个实际存在的可执行文件,对于shell下的内嵌命令是不能直接执行的。

采用Runtime的exec执行程序时,首先要使用Runtime的静态方法得到一个Runtime,然后调用Runtime的exec方

法。可以将要执行的外部程序和启动参数、环境变量、工作目录作为参数传递给exec方法,该方法执行后返回一个Process代表所执行的程序。

Runtime有六个exec方法,其中两个的定义为:

public Process exec(String[] cmdarray, String[] envp, File dir)

public Process exec(String command, String[] envp, File dir)

cmdarray和command为要执行的命令,可以将命令和参数作为一个字符串command传递给exec()方法,也可以将命令和参数一个一个的方在数组cmdarray里传递给exec()方法。

envp为环境变量,以name=value的形式放在数组中。dir为工作目录。

可以不要dir参数,或者不要envp和dir参数,这样就多出了其它4个exec()方法。如果没有dir参数或者为null,那么新启动的

进程就继承当前java进程的工作目录。如果没有envp参数或者为null,那么新启动的进程就继承当前java进程的环境变量。

也可以使用ProcessBuilder类启动一个新的程序,该类是后来添加到JDK中的,而且被推荐使用。通过构造函数设置要执行的命令以及

参数,或者也可以通过command()方法获取命令信息后在进行设置。通过directory(File directory)

方法设置工作目录,通过environment()获取环境变量信息来修改环境变量。

在使用ProcessBuilder构造函数创建一个新实例,设置环境变量、工作目录后,可以通过start()方法来启动新程序,与Runtime的exec()方法一样,该方法返回一个Process对象代表启动的程序。

ProcessBuilder与Runtime.exec()方法的不同在于ProcessBuilder提供了

redirectErrorStream(boolean redirectErrorStream)

方法,该方法用来将进程的错误输出重定向到标准输出里。即可以将错误输出都将与标准输出合并。

2、Process

不管通过那种方法启动进程后,都会返回一个Process类的实例代表启动的进程,该实例可用来控制进程并获得相关信息。Process 类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法:

(1) void destroy()

杀掉子进程。

一般情况下,该方法并不能杀掉已经启动的进程,不用为好。

(2) int exitValue()

返回子进程的出口值。

只有启动的进程执行完成、或者由于异常退出后,exitValue()方法才会有正常的返回值,否则抛出异常。

(3)InputStream getErrorStream()

获取子进程的错误流。

如果错误输出被重定向,则不能从该流中读取错误输出。

(4)InputStream getInputStream()

获取子进程的输入流。

可以从该流中读取进程的标准输出。

(5)OutputStream getOutputStream()

获取子进程的输出流。

写入到该流中的数据作为进程的标准输入。

(6) int waitFor()

导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。

通过该类提供的方法,可以实现与启动的进程之间通信,达到交互的目的。

3、从标准输出和错误输出流读取信息

从启动其他程序的Java进程看,已启动的其他程序输出就是一个普通的输入流,可以通过getInputStream()和getErrorStream来获取。

对于一般输出文本的进程来说,可以将InputStream封装成BufferedReader,然后就可以一行一行的对进程的标准输出进行处理。

4、举例

(1)Runtime.exec()

import java.io.BufferedReader;

import java.io.File;

import java.io.InputStreamReader;

public class Test1 {

public static void main(String[] args) {

try {

Process p = null;

String line = null;

BufferedReader stdout = null;

//list the files and directorys under C:\

p = Runtime.getRuntime().exec("CMD.exe /C dir", null, new File("C:\\"));

stdout = new BufferedReader(new InputStreamReader(p

.getInputStream()));

while ((line = stdout.readLine()) != null) {

System.out.println(line);

}

stdout.close();

//echo the value of NAME

p = Runtime.getRuntime().exec("CMD.exe /C echo %NAME%", new String[] {"NAME=TEST"});

stdout = new BufferedReader(new InputStreamReader(p

.getInputStream()));

while ((line = stdout.readLine()) != null) {

System.out.println(line);

}

stdout.close();

} catch (Exception e) {

e.printStackTrace();

}

}

(2)ProcessBuilder

import java.io.BufferedReader;

import java.io.File;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

public class Test2 {

public static void main(String[] args) {

try {

List list = new ArrayList();

ProcessBuilder pb = null;

Process p = null;

String line = null;

BufferedReader stdout = null;

//list the files and directorys under C:\

list.add("CMD.EXE");

list.add("/C");

list.add("dir");

pb = new ProcessBuilder(list);

pb.directory(new File("C:\\"));

p = pb.start();

stdout = new BufferedReader(new InputStreamReader(p

.getInputStream()));

while ((line = stdout.readLine()) != null) {

System.out.println(line);

}

stdout.close();

//echo the value of NAME

pb = new ProcessBuilder();

mand(new String[] {"CMD.exe", "/C", "echo %NAME%"});

pb.environment().put("NAME", "TEST");

p = pb.start();

stdout = new BufferedReader(new InputStreamReader(p

.getInputStream()));

while ((line = stdout.readLine()) != null) {

System.out.println(line);

}

stdout.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

5、获取进程的返回值

通常,一个程序/进程在执行结束后会向操作系统返回一个整数值,0一般代表执行成功,非0表示执行出现问题。有两种方式可以用来获取进程的返回

值。一是利用waitFor(),该方法是阻塞的,执导进程执行完成后再返回。该方法返回一个代表进程返回值的整数值。另一个方法是调用

exitValue()方法,该方法是非阻塞的,调用立即返回。但是如果进程没有执行完成,则抛出异常。

6、阻塞的问题

由Process代表的进程在某些平台上有时候并不能很好的工作,特别是在对代表进程的标准输入流、输出流和错误输出进行操作时,如果使用不慎,有可能导致进程阻塞,甚至死锁。

如果将以上事例中的从标准输出重读取信息的语句修改为从错误输出流中读取:

stdout = new BufferedReader(new InputStreamReader(p

.getErrorStream()));

那么程序将发生阻塞,不能执行完成,而是hang在那里。

当进程启动后,就会打开标准输出流和错误输出流准备输出,当进程结束时,就会关闭他们。在以上例子中,错误输出流没有数据要输出,标准输出流中

有数据输出。由于标准输出流中的数据没有被读取,进程就不会结束,错误输出流也就不会被关闭,因此在调用readLine()方法时,整个程序就会被阻

塞。为了解决这个问题,可以根据输出的实际先后,先读取标准输出流,然后读取错误输出流。

但是,很多时候不能很明确的知道输出的先后,特别是要操作标准输入的时候,情况就会更为复杂。这时候可以采用线程来对标准输出、错误输出和标准输入进行分别处理,根据他们之间在业务逻辑上的关系决定读取那个流或者写入数据。

针对标准输出流和错误输出流所造成的问题,可以使用ProcessBuilder的redirectErrorStream()方法将他们合二为一,这时候只要读取标准输出的数据就可以了。

当在程序中使用Process的waitFor()方法时,特别是在读取之前调用waitFor()方法时,也有可能造成阻塞。可以用线程的方法来解决这个问题,也可以在读取数据后,调用waitFor()方法等待程序结束。

总之,解决阻塞的方法应该有两种:

(1)使用ProcessBuilder类,利用redirectErrorStream方法将标准输出流和错误输出流合二为一,在用start()方法启动进程后,先从标准输出中读取数据,然后调用waitFor()方法等待进程结束。

如:

import java.io.BufferedReader;

import java.io.File;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

public class Test3 {

public static void main(String[] args) {

try {

List list = new ArrayList();

ProcessBuilder pb = null;

Process p = null;

String line = null;

BufferedReader stdout = null;

//list the files and directorys under C:\

list.add("CMD.EXE");

list.add("/C");

list.add("dir");

pb = new ProcessBuilder(list);

pb.directory(new File("C:\\"));

//merge the error output with the standard output

pb.redirectErrorStream(true);

p = pb.start();

//read the standard output

stdout = new BufferedReader(new InputStreamReader(p

.getInputStream()));

while ((line = stdout.readLine()) != null) {

System.out.println(line);

}

int ret = p.waitFor();

System.out.println("the return code is " + ret);

stdout.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

(2)使用线程

import java.util.*;

import java.io.*;

class StreamWatch extends Thread {

InputStream is;

String type;

List output = new ArrayList();

boolean debug = false;

StreamWatch(InputStream is, String type) {

this(is, type, false);

}

StreamWatch(InputStream is, String type, boolean debug) {

this.is = is;

this.type = type;

this.debug = debug;

}

public void run() {

try {

PrintWriter pw = null;

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String line = null;

while ((line = br.readLine()) != null) {

output.add(line);

if (debug)

System.out.println(type + "" + line);

}

if (pw != null)

pw.flush();

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

public List getOutput() {

return output;

}

}

public class Test5 {

public static void main(String args[]) {

try {

List list = new ArrayList();

ProcessBuilder pb = null;

Process p = null;

// list the files and directorys under C:\

list.add("CMD.EXE");

list.add("/C");

list.add("dir");

pb = new ProcessBuilder(list);

pb.directory(new File("C:\\"));

p = pb.start();

// process error and output message

StreamWatch errorWatch = new StreamWatch(p.getErrorStream(),

"ERROR");

StreamWatch outputWatch = new StreamWatch(p.getInputStream(),

"OUTPUT");

// start to watch

errorWatch.start();

outputWatch.start();

//wait for exit

int exitVal = p.waitFor();

//print the content from ERROR and OUTPUT

System.out.println("ERROR: " + errorWatch.getOutput());

System.out.println("OUTPUT: " + outputWatch.getOutput());

System.out.println("the return code is " + exitVal);

} catch (Throwable t) {

t.printStackTrace();

}

}

}

7、在Java中执行Java程序

执行一个Java程序的关键在于:

(1)知道JAVA虚拟机的位置,即java.exe或者java的路径

(2)知道要执行的java程序的位置

(3)知道该程序所依赖的其他类的位置

举一个例子,一目了然。

(1)待执行的Java类

public class MyTest {

public static void main(String[] args) {

System.out.println("OUTPUT one");

System.out.println("OUTPUT two");

System.err.println("ERROR 1");

System.err.println("ERROR 2");

for(int i = 0; i args.length; i++)

{

System.out.printf("args[%d] = %s.", i, args[i]);

}

}

}

(2)执行该类的程序

import java.util.*;

import java.io.*;

class StreamWatch extends Thread {

InputStream is;

String type;

List output = new ArrayList();

boolean debug = false;

StreamWatch(InputStream is, String type) {

this(is, type, false);

}

StreamWatch(InputStream is, String type, boolean debug) {

this.is = is;

this.type = type;

this.debug = debug;

}

public void run() {

try {

PrintWriter pw = null;

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String line = null;

while ((line = br.readLine()) != null) {

output.add(line);

if (debug)

System.out.println(type + "" + line);

}

if (pw != null)

pw.flush();

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

public List getOutput() {

return output;

}

}

public class Test6 {

public static void main(String args[]) {

try {

List list = new ArrayList();

ProcessBuilder pb = null;

Process p = null;

String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";

String classpath = System.getProperty("java.class.path");

// list the files and directorys under C:\

list.add(java);

list.add("-classpath");

list.add(classpath);

list.add(MyTest.class.getName());

list.add("hello");

list.add("world");

list.add("good better best");

pb = new ProcessBuilder(list);

p = pb.start();

System.out.println(mand());

// process error and output message

StreamWatch errorWatch = new StreamWatch(p.getErrorStream(),

"ERROR");

StreamWatch outputWatch = new StreamWatch(p.getInputStream(),

"OUTPUT");

// start to watch

errorWatch.start();

outputWatch.start();

//wait for exit

int exitVal = p.waitFor();

//print the content from ERROR and OUTPUT

System.out.println("ERROR: " + errorWatch.getOutput());

System.out.println("OUTPUT: " + outputWatch.getOutput());

System.out.println("the return code is " + exitVal);

} catch (Throwable t) {

t.printStackTrace();

}

}

}

进程调度算法模拟程序设计

public class PrivilegeProcess {

public static void main(String[] args) {

MyQueue myqueue = new MyQueue();//声明队列

PCB[] pcb = {new PCB(001,8,1),new PCB(002,7,9),new PCB(003,3,8),new PCB(004,1,7),new PCB(005,7,4)};

PCB para = new PCB();

for(int i=0;ipcb.length;i++){//初始化后首先执行一次排序,这里使用的是选择排序,优先级高的先入队

for(int j=i;jpcb.length;j++){

if(pcb[i].privilege pcb[j].privilege){

para = pcb[i];

pcb[i] = pcb[j];

pcb[j] = para;

}

}

}

System.out.println("初次入队后各进程的顺序:");

for(int i=0;ipcb.length;i++){

System.out.println("初次入队后 # processname : " + pcb[i].name + " totaltime : " + pcb[i].totaltime + " privilege :" + pcb[i].privilege);

}

System.out.println();

myqueue.start(pcb);

}

}

class MyQueue {

int index = 0;

PCB[] pc = new PCB[5];

PCB[] pc1 = new PCB[4];

PCB temp = new PCB();

public void enQueue(PCB process){//入队算法

if(index==5){

System.out.println("out of bounds !");

return;

}

pc[index] = process;

index++;

}

public PCB deQueue(){//出队算法

if(index==0)

return null;

for(int i=0;ipc1.length;i++){

pc1[i] = pc[i+1];

}

index--;

temp = pc[0];

for(int i=0;ipc1.length;i++){

pc[i] = pc1[i];

}

return temp;

}

public void start(PCB[] pc){//显示进程表算法

while(pc[0].isNotFinish==true||pc[1].isNotFinish==true||pc[2].isNotFinish==true||pc[3].isNotFinish==true||pc[4].isNotFinish==true){

//*注意:||运算符,所有表达式都为false结果才为false,否则为true

for(int i=0;ipc.length;i++){

pc[i].run(this);

}

System.out.println();

for(int i=0;ipc.length;i++){//所有进程每执行完一次时间片长度的运行就重新按优先级排列一次

for(int j=i;jpc.length;j++){

if(pc[i].privilege pc[j].privilege){

temp = pc[i];

pc[i] = pc[j];

pc[j] = temp;

}

}

}

}

}

}

class PCB {//声明进程类

int name,totaltime,runtime,privilege;

boolean isNotFinish;

public PCB(){

}

public PCB(int name, int totaltime, int privilege){

this.name = name;//进程名

this.totaltime = totaltime;//总时间

this.privilege = privilege;//优先级别

this.runtime = 2;//时间片,这里设值为2

this.isNotFinish = true;//是否执行完毕

System.out.println("初始值: processname : " + name + " totaltime : " + totaltime + " privilege :" + privilege );

System.out.println();

}

public void run (MyQueue mq){//进程的基于时间片的执行算法

if(totaltime1){

totaltime-=runtime;//在总时间大于1的时候,总时间=总时间-时间片

privilege--;

System.out.println(" processname : " + name + " remaintime : " + totaltime + " privilege :" + privilege );

}else if(totaltime==1){

totaltime--;//在总时间为1时,执行时间为1

privilege--;

System.out.println(" processname : " + name + " remaintime : " + totaltime + " privilege :" + privilege );

}else{

isNotFinish = false;//总时间为0,将isNotFinish标记置为false

}

if(isNotFinish==true){

mq.deQueue();

mq.enQueue(this);

}

}

}

用Java程序写一个彩票的模拟程序生成6个红球(1-33的随机数),1个蓝球(1-16的随机数),随机数可以重复

import java.util.Random;

import java.util.Scanner;

public class DoubleBalls {

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("是否机选一组双色球号码?(Y/N)");

Scanner input = new Scanner(System.in);

char a = input.next().charAt(0); // 输入一个char字符,0位即是第一位

if (a == 'Y' || a == 'y') {

Random suiji = new Random(); // 创建suiji方法

int blue = suiji.nextInt(16);//从0到16中选一个数字个蓝球

while(blue==0){

blue=suiji.nextInt(16);

}//如果选到了0,再选一次给blue

int red[] = new int[6];// 用一个6个元素的数组装红球

for (int i = 0; i 6; i++) {

red[i] = suiji.nextInt(33); // 随机分配0到33的整数

if (red[i] == 0) {i--;}

if (i == -1) {i = 0;}

for (int j = 0; j i; j++) {

while (red[i] == red[j]) {i--;}// 发现相同的从新回去生成一个

}

}

System.out.print("红球:");

for (int k = 0; k red.length; k++) {

System.out.print(red[k] + " ");// 输出数组red

}

System.out.print("蓝球:"+blue);

} else

System.out.println("fuck you~");

}

}

应该可以了,可以产生一组。。。如果楼主你中头奖了,送我套房好了哈^0^


文章题目:模拟进程代码java,进程调度模拟程序
文章来源:http://chengdu.cdxwcx.cn/article/hdhpcp.html