主方法关闭后如何运行线程? [英] How can thread run after main method closes?

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

问题描述

以下是我的两个类:

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...");
    }
}

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);   
        }
    }
}

现在我运行 Firstclass 然后输出为:

Now when I run Firstclass then the output is:

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

我的第一个问题是:我想知道为什么两个线程仍在运行,即使 main 方法已经完成?

My first question is: I want to know why both threads are still running even though the main method have finished?

我的第二个问题是:任何人都可以向我解释方法 join synchronized 之间的区别是什么?

My second question is: can anybody explain to me what the difference is between methods join and synchronized?

推荐答案

您的主题未关闭 -

Your main thread is not closed -

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

问题的第2部分 - <$ c $之间没有联系c> join 和 synchronized 。它们几乎相反。

On part 2 of your question - There is no connection between join and synchronized. They are almost opposite.


  • join - 在恢复之前等待线程完成。

  • synchronized - 这里只能输入一个线程,所有其他线程必须等待。

  • join - Wait for the thread to complete before resuming.
  • synchronized - Only one thread can enter here, all others must wait.

这篇关于主方法关闭后如何运行线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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