Java 多线程 thread.sleep()

标签 java multithreading

我刚开始接触 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/

相关文章:

java - Quarkus 如何指定 JNDI 数据源

java - 如何防止ArrayList的结构被修改?

java - 如何使用 LUNA HSM 签署 PDF 文档?

c++ - 如何在不让用户等待的情况下管理多个线程?

java - 如何使缓冲读取器从头开始读取而不是使用另一个对象

java - 配置 WSO2 API 管理器自定义身份 validator 和声明

Java - 等待 Runnable 完成

c++ - 停止 MFC 线程

c++ - 错误 : ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function

c++ - 使用字符串参数创建 SDL_thread