Java线程如何工作 [英] How does Java Threads work

查看:78
本文介绍了Java线程如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名Java学习者,试图了解Threads.

I'm a Java learner, trying to understand Threads.

我期望下面的程序按顺序输出

I was expecting output from my program below, in the order

线程启动运行方法再见

Thread started Run Method Bye

但是我按顺序得到输出

Bye Thread启动了运行方法

Bye Thread started Run Method

这是我的代码:

public class RunnableThread
{
    public static void main(String[] args)
    {
        MyThread t1= new MyThread("Thread started");
        Thread firstThread= new Thread(t1);
        firstThread.start();
        System.out.println("Bye");
    }
}

class MyThread implements Runnable
{
    Thread t;
    String s= null;

    MyThread(String str)
    { 
      s=str;
    }

    public void run()
    {
      System.out.println(s);
      System.out.println("Run Method");
    }
}

推荐答案

在多线程代码中,不能保证哪个线程将以什么顺序运行.那是多线程的核心,而不仅限于Java.您可以一次获得t1,t2,t3的顺序,另一次获得t3,t1,t2的顺序.

In a multithreaded code there's no guarantee which thread will run in what order. That's in the core of multithreading and not restricted to Java. You may get the order t1, t2, t3 one time, t3, t1, t2 on another etc.

在您的情况下,有2个线程.一个是主线程,另一个是firstThread.尚不确定哪个先执行.

In your case there are 2 threads. One is main thread and the other one is firstThread. It's not determined which will execute first.

这篇关于Java线程如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆