简体   繁体   English

主方法关闭后如何运行线程?

[英]How can thread run after main method closes?

Here are my two classes: 这是我的两个班级:

public class Firstclass {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Main start....");
        Secondclass t1 = new Secondclass();
        t1.setName("First Thread");
        Secondclass t2 = new Secondclass();
        t2.setName("Second Thread");
        t1.start();
        t2.start();
        System.out.println("Main close...");
    }
}

and

public class Secondclass extends Thread {
    @Override
    public void run() {
        try {
            loop();
        } catch(Exception e) {
            System.out.println("exception is" + e);
        }
    }

    public void loop() throws InterruptedException {
        for(int i = 0; i <= 10; i++) {
            Thread t = Thread.currentThread();
            String threadname = t.getName();
            if(threadname.equals("First Thread")) {
                Thread.sleep(1000);
            } else {
                Thread.sleep(1500);
            }
            System.out.println("i==" + i);   
        }
    }
}

Now when I run Firstclass then the output is: 现在,当我运行Firstclass ,输出是:

Main start....
Main close...
i==0
i==0
i==1
i==1
i==2
i==3
i==2
i==4
i==3
i==5
i==6
i==4
i==7
i==5
i==8
i==9
i==6
i==10
i==7
i==8
i==9
i==10

My first question is: I want to know why both threads are still running even though the main method have finished? 我的第一个问题是:我想知道为什么即使main方法已经完成,两个线程仍在运行?

My second question is: can anybody explain to me what the difference is between methods join and synchronized ? 我的第二个问题是:任何人可以向我解释方法joinsynchronized之间的区别是什么?

I want to know that even though the main method is closed How are both threads still running? 我想知道即使main方法已关闭,两个线程仍在运行?

The JVM will exit once the last non-jvm thread terminates. 一旦最后一个非jvm线程终止,JVM将退出。 this means that if any of the threads you create is still running, the jvm will not shutdown. 这意味着如果您创建的任何线程仍在运行,则jvm将不会关闭。 daemon threads are threads that do not prevent the JVM from shutting down. 守护程序线程是不阻止JVM关闭的线程。 normally you'd use them for some background tasks which you dont want keeping your application up if the user requested it to shut down. 通常你会将它们用于某些后台任务,如果用户要求它关闭,你不希望保留你的应用程序。

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. 守护程序线程是一个线程,当程序完成但线程仍在运行时,它不会阻止JVM退出。 An example for a daemon thread is the garbage collection. 守护程序线程的一个示例是垃圾回收。

You can use the setDaemon() method to change the Thread daemon properties. 您可以使用setDaemon()方法更改Thread守护程序属性。 By default, every thread that a user create is a normal (non-daemon) thread, unless you explicitly call setDaemon() method. 默认情况下,除非您显式调用setDaemon()方法,否则用户创建的每个线程都是普通(非守护程序)线程。

explain me what is the difference between join method and synchronized 解释一下join方法和synchronized之间有什么区别

Synchronization is a locking mechanism that allows two threads to not step on each other ie synchronization is used to provide proper access to shared resources by multiple threads with the help of locking mechanism. 同步是一种锁定机制,它允许两个线程不相互踩踏,即同步用于在锁定机制的帮助下通过多个线程提供对共享资源的适当访问。
On the other hand join() method call allows one thread to wait for the completion of another thread. 另一方面, join()方法调用允许一个线程等待另一个线程的完成。

Your first question, 你的第一个问题,

When main method is called by default one main thread is created. 默认情况下调用main方法时,会创建一个主线程。 And main thread is a non-dameon thread. 主线程是非dameon线程。 When threads created by the main method it inherits it's parant's property. 当main方法创建的线程继承它的parant的属性时。 That means they are all non-daemon threads. 这意味着它们都是非守护程序线程。 As you know JVM waits until all non-daemon threads to complete. 如您所知,JVM会等待所有非守护程序线程完成。 So it will executes even after the main thread completes. 所以它甚至会在主线程完成后执行。

See here : daemon vs non-daemon Java Stack for each thread creation 请参阅此处: 每个线程创建的 守护程序与非守护程序 Java堆栈

and your second question: join method joins the currently running thread at the end of the thread which is calling the join method. 和你的第二个问题:join方法在调用join方法的线程的末尾加入当前运行的线程。 That means the current thread will be stopped and it start after the thread referenced by the join method. 这意味着当前线程将被停止,并在join方法引用的线程之后启动。

Synchronization stops two threads executing the same code at the same time. 同步会停止两个线程同时执行相同的代码。

I want to know that even though the main method is closed How are both threads still running? 我想知道即使main方法已关闭,两个线程仍在运行?

Your main() method was run by a separate thread, which start another two threads ( First ad Second ). 你的main()方法是由一个单独的线程运行的,它开始另外两个线程( First广告Second )。 All Threads are not depend on each other, so, main thread can print the line below the starting line of other threads. 所有线程都不相互依赖,因此,主线程可以打印其他线程起始行下面的行。

My second question is can anybody explain me what is the difference between join method and synchronized? 我的第二个问题是,任何人都可以解释一下join方法和synchronized之间的区别是什么?

join() means waiting for a thread to complete. join()表示等待线程完成。 This is a blocker method. 这是一种阻止方法。 synchronized is a keyword to denote that, multiple thread can't access a synchronized block/method synchronously. synchronized是一个关键字,表示多线程无法同步访问同步块/方法。

join If you have a thread B that can't do its work until another thread A has completed its work, then you want thread B to "join" thread A. join如果你有一个线程B在另一个线程A完成其工作之前无法完成其工作,那么你希望线程B“加入”线程A.

synchronized When we use threads, we usually need to use some synchronization somewhere to make sure our methods don't interrupt each other at the wrong time and mess up our data. synchronized当我们使用线程时,我们通常需要在某处使用某种同步来确保我们的方法不会在错误的时间互相中断并弄乱我们的数据。 Generally, any time more than one thread is accessing mutable (changeable) data, you synchronize to protect that data, to make sure two threads aren't changing it at the same time (or that one isn't changing it at the same time the other is reading it, which is also confusing). 通常,在多个线程访问可变(可更改)数据的任何时候,您同步以保护该数据,以确保两个线程不会同时更改它(或者一个线程不会同时更改它另一个是阅读它,这也令人困惑)。

There are two types of threads user and daemon. 用户和守护程序有两种类型的线程。 So if you want your program to exit make your thread a daemon. 因此,如果您希望程序退出,请将您的线程作为守护程序。

Example

Thread t = new Thread();
t.setDaemon(true);

The process terminates when there are no more user threads. 当没有更多用户线程时,该进程终止。

To your second Question: 至于你的第二个问题:

Join is to be used only when you need to ensure that the thread dies & you have nothing to do after that 只有在需要确保线程死亡且之后无所事事时才使用Join

Synchronization is for inter-thread-communication 同步用于线程间通信

Your main thread is not closed - 你的main未关闭 -

      // ...
      System.out.println("Main close...");
      // <--- Your main method is here while all the other threads complete (sort of).
     }

On part 2 of your question - There is no connection between join and synchronized . 关于你的问题的第二部分-有没有关系的joinsynchronized They are almost opposite. 他们几乎相反。

  • join - Wait for the thread to complete before resuming. join - 在恢复之前等待线程完成。
  • synchronized - Only one thread can enter here, all others must wait. synchronized - 只有一个线程可以进入此处,其他线程必须等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Java应用程序中从Main方法运行线程? - How can I run thread from Main method in Java application? 调用run方法后,主线程是否被另一个线程中断? - Main thread being interrupted by another thread after run method is called? 主线程如何将信息传输到子线程(如何在run方法中处理消息?)? - How does the main thread transmit information to the child thread (How can I handle message in the run method?)? 主线程中的 run() 方法完成后我的程序不会停止 - My program will not stop after run() method in main thread finishes 在所有其他线程完成后如何在最后运行主线程 - how to run main thread at the end after all other threads completed 当离开主线程时,如何才能使一些代码尽快在主线程上运行? - When off the main thread, how can I get some code to run on the main thread as quickly as possible? 如何在“主”线程上运行DefaultMessageListenerContainer - How to run DefaultMessageListenerContainer on the 'main' thread 在主线程/程序终止上运行方法? - Run a method on main thread/program termination? 如何将主线程作为实时线程运行 - How to run main thread as a real time thread timertask完成后,在主线程中调用方法 - Call method in main thread after timertask completes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM