无法理解线程-可运行接口的工作方式 [英] Unable to understand the working of Threads- Runnable Interface

查看:58
本文介绍了无法理解线程-可运行接口的工作方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test {
    private static void funct(final int i) {
        new Thread(new Runnable() {
            public void run() {System.out.println(i);}
         }).start(); 
    }
    public static void main(String[] args) {
        System.out.println(1);
        funct (2);
        System.out.println(3);
        funct (4);
        System.out.println(5);
    }
}

每次运行它,我都会得到以下解决方案之一.为什么这样? 1个 3 5 4 2

Every time I run it, I am getting one of the below solutions. Why so? 1 3 5 4 2

1 3 5 2个 4

1 3 5 2 4

1 3 2个 5 4

1 3 2 5 4

推荐答案

在此示例中,数字的打印顺序不确定.您唯一可以确定的是,1、3和5将按该顺序出现.但是,这种排列2和4的位置未知.原因是您有3个线程打印出以下数字系列:(1、3、5); (2)和(4).这三个线程将由JVM调度,但是它确定是最佳的.

The order at which the numbers will be printed out is indeterminate in this example. The only thing you know for sure is that 1, 3, and 5 will appear in that order. But where in this arrangement 2 and 4 will come is unknown. The reason for this is you have 3 threads printing out the following number series: (1, 3, 5); (2), and (4). The three threads will be scheduled by the JVM however it determines would be best.

多线程编程是一个复杂的主题,由于它看起来像您才刚刚开始涉足,因此我建议使用Oracle Java教程的Concurrency部分:

Multithreaded programming is a complex topic, and since it looks like you are just starting to dive into it I would recommend the Concurrency portion of Oracle's Java tutorial: http://download.oracle.com/javase/tutorial/essential/concurrency/index.html

这篇关于无法理解线程-可运行接口的工作方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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