gpt4 book ai didi

java - 在多线程中,为什么当我暂停一个线程执行时其他线程不工作

转载 作者:行者123 更新时间:2023-12-01 16:45:51 25 4
gpt4 key购买 nike

我的编程中有三个线程。根据线程概念,所有线程都是异步运行的。所以每个线程都是由处理器随机执行的。如果我刚刚使用 thread.sleep() 暂停了一个线程的执行,那么其他线程应该可以工作。正确的??当线程的 sleep 时间结束时,它应该再次继续执行。但就我而言,当我使用 t2.sleep(10000) 暂停一个线程时,所有其他线程也会暂停。但当 t2 线程处于等待状态时,它们应该可以正常工作。谁能告诉我为什么会这样?

    import java.util.*;
class square extends Thread
{
public int x;
public square(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Square of the number is " + x*x);
}
}
class cube extends Thread
{
public int x;
public cube(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Cube of the number is " + x*x*x);
}
}

class randgen extends Thread
{
public void run()
{
int num=0;
Random r = new Random();
try
{
for(int i=0;i<5;i++)
{
num = r.nextInt(100);
System.out.println("The number generated is " + num);
square t2 = new square(num);
t2.start();
t2.sleep(10000);
cube t3 = new cube(num);
t3.start();

}
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
public class Main
{
public static void main(String args[])
{
randgen obj = new randgen();
obj.start();

}
}

输出

The number generated is 50
Square of the number is 2500
(After 10s) Cube of the number is 125000
The number generated is 36
Square of the number is 1296
(After 10s)
The number generated is 75
Cube of the number is 46656
Square of the number is 5625
(After 10s)
The number generated is 92
Cube of the number is 421875
Square of the number is 8464
(After 10s)
The number generated is 0
Cube of the number is 778688
Square of the number is 0 (After 10s)
Cube of the number is 0

为什么我在 10 秒后得到输出,而不是根据线程的概念,我暂停的线程应该只暂停 10 秒,其他线程应该同步工作。

最佳答案

Thread.sleep 是一个静态方法。调用 t2.sleep(10000) 不会暂停 t2,而是暂停当前线程。所以你实际上要做的是启动 t2,等待 10 秒,然后启动 t3。如果您想暂停线程 t2,请不要从 randgen 调用 t2.sleep(10000),而是从 square.run 内部调用 Thread.sleep(10000) ().

  public void run()
{
Thread.sleep(10000);
System.out.println("Square of the number is " + x*x);
}

关于java - 在多线程中,为什么当我暂停一个线程执行时其他线程不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51123491/

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