java - 基本 Java 线程和可运行模式

标签 java multithreading runnable

我无法理解这段代码。我对 Java 的了解只有几个小时。

这是代码:

// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }

   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

public class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

这是它的输出:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

这是我的问题。

我想了解代码遵循的模式。据我所知,

  • 首先,程序应该开始执行main()函数。因此,应该初始化 NewThread 的实例。
  • 然后,我必须进入 NewThread 构造函数并编写 Child thread: Thread[Demo Thread,5,main]
  • 之后 t.start() 到来,因此程序应该执行 public void run() (我错了吗??)

public void run()中,我想我应该得到一个输出子线程5,但我得到了主线程5 。我想知道为什么 ??

有谁能帮帮我吗?提前致谢。

最佳答案

t.start() 创建一个新线程,并从中调用 run()。此时,有两个线程独立运行:一个是调用 start() 的线程,另一个是新线程。原始线程从构造函数返回,然后开始执行 main() 方法中的循环。

由于两个线程是独立的,因此无法保证哪个线程将首先调用 System.out.println。在您给出的示例输出中,碰巧原始线程首先打印。但反过来也很容易发生。

顺便说一句,如果您是 Java 新手,我建议您在学习线程之前学习该语言的基础知识。您的问题中没有任何内容表明您感到困惑,但线程是一个相对高级的主题,在您达到这一步之前,值得先熟悉一般的语言行为,IMO。这样您就可以确信您看到的任何奇怪行为确实是由于线程造成的,而不是由于误解了语言的其他部分。

关于java - 基本 Java 线程和可运行模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19363920/

相关文章:

java - 升级到Struts 2.3.32后出现404错误

java - PrintStackTrace 导致我的程序崩溃。为什么?

java - 无法使用正确的 list 执行使用 gradle 构建的 jar

c# - wpf mvvm 等待方法在使用 await 任务延迟进行模拟时阻止 UI

java - 如何使 JButton 沿着绘制的线条移动

android - 如何将 Toast 放入服务的 Runnable 中?

android - 媒体播放器搜索栏问题

java - Android audioRecord.read 缓冲区连接以制作波形

python - 在线程中运行 bash 脚本不阻塞主循环

java - 多线程:将实例和局部变量传递给线程