是的,这是一项家庭作业,但我已经尽了一切可能,但却找不到可能。这个任务的重点是说明在实现dekker算法/ peterson算法之前,两个进程很可能不会一个接一个地进行。
import java.util.*;
public class myProcess
{
private static final Random R = new Random();
private int id;
public myProcess(int i){
id = i;
}
private static void delay(int value){
try{
java.lang.Thread.sleep(R.nextInt(value));
}
catch(InterruptedException e){
}
}
public void run(){
System.out.println("");
delay(20);
System.out.println(this.id + " is starting");
delay(20);
System.out.println("LINE ONE");
delay(20);
System.out.println("LINE TWO");
delay(20);
System.out.println("LINE THREE");
delay(20);
System.out.println(this.id+ " is ending ");
delay(20);
}
public static void main(String [] args){
final int N = 2;
myProcess[] t = new myProcess[N];
for(int i = 0; i < N; i++){
t[i] = new myProcess(i);
t[i].run();
}
}
现在输出
0 is starting
LINE ONE
LINE TWO
LINE THREE
0 is ending
1 is starting
LINE ONE
LINE TWO
LINE THREE
1 is ending
但它应该是混合起来,以说明进程不一定等待另一个进程完成。
我尝试了其他定义run()的方法,例如
String[] statements = new String[5];
statements[0] = "Thread " + this.id + " is starting iteration ";
statements[1] = "We hold these truths to be self-evident, that all men are created equal,";
statements[2] = "that they are endowed by their Creator with certain unalienable Rights,";
statements[3] = "that among these are Life, Liberty and the pursuit of Happiness.";
statements[4] = "Thread " + this.id+ " is done with iteration ";
for(int i = 0; i< 5; i++){
System.out.println(statements[i]);
delay(20);
}
但它仍然没有给我任何“错误的输出”
我做错了什么让输出如此正确?
答案 0 :(得分:2)
您应该在线程上调用start()
函数,而不是run()
。
编辑:您的类也应该实现Runnable
接口或扩展Thread
类。
您没有在代码中创建新的线程,并且所有内容都在一个线程中运行。
public class myProcess extends Thread
...
for(int i = 0; i < N; i++){
t[i] = new myProcess(i);
t[i].start();
}
答案 1 :(得分:0)
我猜你的延迟时间太短,看不到任何明显的混音。你传入20,好像它是20秒,但它只有20毫秒的睡眠。通过20,000,看看你是否得到了你期望的行为。
答案 2 :(得分:0)
将延迟方法更改为如下所示。根据这篇文章(https://stackoverflow.com/a/1600603/1265692),Java sleep方法不能保证放弃对cpu的控制。通过添加yield调用,您可以提醒Java让其他线程运行。
private static void delay(int value){
try{
java.lang.Thread.sleep(R.nextInt(value));
java.lang.Thread.yield();
}
catch(InterruptedException e){
}
}