线程如何在Java中工作以及它们的工作方式与方法中的基本代码有何不同? [英] How threads work in Java and how their working is different from basic code inside a method?

查看:73
本文介绍了线程如何在Java中工作以及它们的工作方式与方法中的基本代码有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上这段代码有两个在两个类中创建的线程,它们是从第三个类中调用的。每个线程都有一个循环,并在每次迭代后休眠。

Basically this code has two threads created in two classes, and they are called from the third class. Each thread has a loop, and it sleeps after each iteration.

(代码到底)

输出为:

CHECK 0 CHECK
CHECK 1 CHECK
run one
in thread1 
CHECK 2 CHECK
run two
in thread2

1)我不知道它为什么会这样运作。我的意思是可以先打印CHECK 0 CHECK。但是为什么CHECK 1 CHECK在Thread1之前打印(而在代码中调用Thread1之后)和CHECK 2 CHECK和Thread2相同?

1) I am not getting any idea why it works this way. I mean it is okay that CHECK 0 CHECK should be printed first. But why does CHECK 1 CHECK get printed before Thread1 (whereas it comes after Thread1 is called in the code) and same for CHECK 2 CHECK and Thread2?

2)如果我将CHECK 2 CHECK替换为System.exit(0),如上例所示,在运行Thread2之前,在Thread2旁边打印CHECK 2 CHECK,为什么在运行Thread2之后发生System.exit(0) case?

2) If i replace CHECK 2 CHECK with System.exit(0), as in the case above, where printing CHECK 2 CHECK, which is next to Thread2, takes place before running Thread2, Why is System.exit(0) happening after running Thread2 in this case?

第二种情况的输出:

CHECK 0 CHECK
CHECK 1 CHECK
run one
in thread1 
run two
in thread2

请说明为什么会这样?为什么方法中的线程和代码会以这种方式混淆?
我想我对java如何管理线程一无所知。我尝试了很多,但找不到任何我能理解的东西。

Please tell why this is happening? Why are the threads and code in method, getting mixed up this way? I think i don't have any idea about how threads are managed by java. I tried searching a lot, but could not find anything that i could understand.

代码:

public class Thread1 implements Runnable 
{

    public Thread1()
    {
        new Thread(this).start();
    }

    public void run() 
    {
        // TODO Auto-generated method stub
        System.out.println("run one");
        try
        {
            for(int i = 0; i < 5;i++)
            {
                System.out.println("in thread1 ");
                Thread.sleep(1000);
            }
        }
        catch(Exception e)
        {
            //e.printStackTrace();
        }
    }

}

public class Thread2 implements Runnable 
{

    public Thread2()
    {
        new Thread(this).start();
    }

    public void run() 
    {
        // TODO Auto-generated method stub
        System.out.println("run two");
        try
        {
            for(int i=0;i<5;i++)
            {
                System.out.println("in thread2 ");
                Thread.sleep(1000);
            }
        }
        catch(Exception e)
        {
            //e.printStackTrace();
        }
    }
}

public class Threadjava
{
    public static void main(String[] str)
    {
        System.out.println("CHECK 0 CHECK");
        new Thread1();
        System.out.println("CHECK 1 CHECK");
        new Thread2();
        System.out.println("CHECK 2 CHECK");
        //The above is deleted in the second case
        System.exit(0);
        System.out.println("CHECK 3 CHECK");
    }
}


推荐答案

好,这是一个常见的误解,即java程序本质上是单线程的,因为它们不是。
当你启动一个java程序时,它正在Java虚拟机中执行,它启动了几个其他线程来执行你的代码。查看这个不错的博客:

Well, this is a common misconception, that java programs are single threaded by nature, because they are not. When you start a java program it's being executed inside a Java Virtual Machine, which starts several other threads to execute your code. Check this nice blog:

http://blog.jamesdbloom。 com / JVMInternals.html #jvm_system_threads

在你的情况下,你最重要的是,你启动一个执行main方法的主线程。从那里开始两个独立的线程Thread1和Thread2,它们被安排执行,但你不知道它们何时被OS调度程序选中以实际执行。由于许多原因,它不具有确定性:

In your case you most important is, that you start a main thread, which executes a main method. From there you start two separate threads Thread1 and Thread2, which are being scheduled to be executed, but you don't know when they will be picked up by the OS scheduler to be actually executed. It's not deterministic for many reasons:


  • 你不知道算法调度程序用来获取要执行的线程,

  • 您不知道您的处理器有多少核心,您的线程可以并行或串行运行

  • Just In Time编译器可能会重新排列和优化您的代码,

  • CPU可能会重新排列对IO的读写操作以优化代码的执行,

  • 您的代码中可能存在导致数据争用的错误,竞争条件,starvations等。

  • you don't know what algorithm scheduler is using to pick up threads to be executed,
  • you don't know how many cores your processors have, your threads might run in parallel or serially
  • Just In Time compiler might rearrange and optimise your code,
  • CPU might rearrange reads and writes to IO to optimise the execution of your code,
  • you might have bugs in your code that lead to data races, race conditions, starvations etc.

Java并发是一个难题,我发给你的博客条目是一个好地方开始吧,顺其自然。
如需认真阅读,请访问 http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz / dp / 0321349601

Java concurrency is a hard topic and the blog entry that I've sent you is a good place to start, go with it. For serious reading go here http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601.

祝你好运。

这篇关于线程如何在Java中工作以及它们的工作方式与方法中的基本代码有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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