我刚开始接触 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);
thread1
和thread0
是同一个线程吗?
另外,我还没有在我的代码中的任何地方启动 thread1
那么为什么线程会进入 hibernate 状态?
我只是多线程的初学者,引用了 Java The Complete 引用书。
最佳答案
Thread.sleep(...)
方法导致当前线程 hibernate 。它是静态方法,不是实例方法。
没有安全的方法可以让一个线程强制另一个线程 hibernate 。
你还犯了其他错误:
创建
Thread
的子类通常是错误的。执行线程的推荐方法是编写一个实现Runnable
的类,并创建java.lang.Thread
的实例作为您的线程。更好的是,使用线程池、fork-join 池或ExecutorService
实例。在此:
Mythread mythread = new Mythread(); Thread thread = new Thread(mythread, "thread0");
您实际上是将
mythread
对象用作(仅)Runnable
。您在
run()
方法中创建的线程从未被使用……因为您从未启动它们。但是如果你这样做了,就会出现线程爆炸......因为你正在用this
作为Runnable
和run()
实例化它们> 方法只会创建更多线程。有许多 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/