gpt4 book ai didi

Java 多线程 thread.sleep()

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:09 25 4
gpt4 key购买 nike

我刚开始接触 Java 的多线程概念。我写了一个小的 Java 程序,但是,我真的无法理解它的行为。

public class Mythread implements Runnable{

@Override
public void run() {
System.out.println("mythread: ");
Thread t=new Thread(this,"thread1");

for(int i=1;i<5;i++)
{
System.out.println("in for of myThread");

try {
t.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}


public class ThreadTest {

public static void main(String[] args) {
System.out.println("in main thread");
Mythread mythread=new Mythread();
Thread thread=new Thread(mythread,"thread0");
thread.start();

for(int i=1;i<5;i++)
{
System.out.println("main class: "+i);
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

现在,当我执行上面的程序时,我看到当线程 1 进入休眠状态时,线程 0 也进入休眠状态。

t.sleep(1000);

thread1thread0 是同一个线程吗?另外,我还没有在我的代码中的任何地方启动 thread1 那么为什么线程会进入 hibernate 状态?

我只是多线程的初学者,引用了 Java The Complete 引用书。

最佳答案

Thread.sleep(...) 方法导致当前线程 hibernate 。它是静态方法,不是实例方法。

没有安全的方法可以让一个线程强制另一个线程 hibernate 。


你还犯了其他错误:

  1. 创建Thread 的子类通常是错误的。执行线程的推荐方法是编写一个实现 Runnable 的类,并创建 java.lang.Thread 的实例作为您的线程。更好的是,使用线程池、fork-join 池或 ExecutorService 实例。

  2. 在此:

    Mythread mythread = new Mythread();
    Thread thread = new Thread(mythread, "thread0");

    您实际上是将 mythread 对象用作(仅)Runnable

  3. 您在 run() 方法中创建的线程从未被使用……因为您从未启动它们。但是如果你这样做了,就会出现线程爆炸......因为你正在用 this 作为 Runnablerun() 实例化它们> 方法只会创建更多线程。

  4. 有许多 Java 风格违规......从您选择 Mythread 作为类名开始。


回答您的问题:

is thread1 and thread0 refers to same thread ?

没有。

Also I haven't started thread1 anywhere in my code then why thread goes to sleep ?

其实是thread0要 hibernate 了。如果你改变

System.out.println("in for of myThread");

System.out.println("in for of myThread: " + Thread.currentThread());

你会看到...

关于Java 多线程 thread.sleep(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754309/

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