gpt4 book ai didi

java - 即使没有 dekker/peterson 的算法,Java 中的多线程也能工作吗?

转载 作者:行者123 更新时间:2023-12-02 06:00:03 25 4
gpt4 key购买 nike

是的,这是一项家庭作业,但我已经尝试了所有可能的方法,但无法想出一个可能的方案。这个作业的目的是为了说明,在实现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);
}

但它仍然没有返回给我任何“错误的输出”

我做错了什么,导致输出如此正确?

最佳答案

您应该在线程上调用 start() 函数,而不是 run()

编辑:您的类还应该实现 Runnable 接口(interface)或扩展 Thread 类。

您没有在代码中创建新线程,所有内容都在一个线程中运行。

public class myProcess extends Thread

...

for(int i = 0; i < N; i++){
t[i] = new myProcess(i);
t[i].start();
}

关于java - 即使没有 dekker/peterson 的算法,Java 中的多线程也能工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22753034/

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