gpt4 book ai didi

Java 线程 新线程顺序

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:54 24 4
gpt4 key购买 nike

//Class PrintTask sleeps between0-5 seconds
import java.util.Random;
public class PrintTask implements Runnable{
private final int sleeptime;
private final String taskname;
private final static Random generator= new Random();

public PrintTask(String name)
{
taskname=name;
sleeptime=generator.nextInt(5000);

}

public void run()
{
try
{
System.out.printf("%s going to sleep for %d ms.\n", taskname,sleeptime);
Thread.sleep(sleeptime);

}
catch(InterruptedException exception)
{
System.out.printf("%s %s\n", taskname,"terminated prematurely due to interruption");
}
System.out.printf("%s done sleeping\n",taskname);



}

}


//Creation and start of three threads
import java.lang.Thread;
public class Threads {

public static void main(String[] args) {
System.err.println("Creating threads");
Thread thread1=new Thread(new PrintTask("task1"));
Thread thread2=new Thread(new PrintTask("task2"));
Thread thread3=new Thread(new PrintTask("task3"));

thread1.start();
thread2.start();
thread3.start();
System.err.println("Tasks Started. Main Ends. \n");
}

}

一些结果

task2 going to sleep for 320 ms.
task1 going to sleep for 3054 ms.
task3 going to sleep for 1821 ms.
task2 done sleeping
task3 done sleeping
task1 done sleeping

task2 going to sleep for 1338 ms.
task3 going to sleep for 2825 ms.
task1 going to sleep for 3461 ms.
task2 done sleeping
task3 done sleeping
task1 done sleeping

我的问题是为什么消息“任务”将 hibernate **毫秒,没有以正确的顺序出现,如下所示:(有时它可能以“正确”的顺序出现)

task1 going to sleep for **** ms.
task2 going to sleep for **** ms.
task3 going to sleep for **** ms.

但它似乎以随机顺序出现。我是线程新手,所以请尽可能简单地回答我。谢谢!

最佳答案

您正在创建线程并将它们发送到某种调度程序。

这些线程由 JVM(或操作系统)启动,没有特殊的顺序。

更新:

正如@Braj在评论中提到的,您可以通过设置线程优先级来影响执行顺序。

关于Java 线程 新线程顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886591/

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