Java线程–优雅关闭

2018年10月13日

不建议用stop 操作, 比较粗鲁, 会导致其可能的一些锁被粗暴的释放,导致一些场景下的数据不一致;

 

样例1 :interrupt方法

public class ThreadStopGraceful1 implements Runnable {
    
    public void run() {

        while(true) {
            if (Thread.currentThread().isInterrupted){                    
                 System.out.println(Thread.currentThread().getName() + ": " + i);
                 break;  //通过break跳出循环,从而也结束了run()所在线程
            }
            Thread.yield();
        }
           
        
    }

    public static void main(String args[]) throws InterruptedException {
            ThreadStopGraceful t1=new ThreadStopGraceful1();
            Thread t=new Thread(t1);
            t.setName("t1");
            t.start();
            Thread.sleep(8000);
            t.interrupt();
        }
    }

 

 

样例2:使用标志位+ interrupt方法:

public class ThreadStopGraceful2 implements Runnable {
    boolean isRun = true;

    public boolean isRun() {
        return isRun;
    }

    public void setRun(boolean run) {
        isRun = run;
    }

    public void run() {
       
        for (int i = 0; i < 10; i++) {
            if (Thread.currentThread().isInterrupted){                    
                 System.out.println(Thread.currentThread().getName() + ": " + i);
                 break;  //通过break跳出循环,从而也结束了run()所在线程
            }
            if (isRun) {
                System.out.println(Thread.currentThread().getName() + ": " + i);

                try {
                    Thread.sleep(2000);//recive interrupt when thread is sleep
                } catch (InterruptedException e) {
                    System.out.println("interrupted when sleep");
                    Thread.currentThread().interrupt();//抛出异常后,中断标志会被清空,需要再次设置中断标志,防止后续循环终端标志失效
                    e.printStackTrace();
                }
            } else {
                return;
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {
            ThreadStopGraceful t1=new ThreadStopGraceful();
            Thread t=new Thread(t1);
            t.setName("t1");
            t.start();
            Thread.sleep(8000);
            t1.setRun(false);

        }
    }

 

46条评论

  • luxury homes 2018年11月26日在上午6:28

    This is very interesting, You’re a very skilled blogger. I have joined
    your rss feed and look forward to seeking more of your excellent post.

    Also, I’ve shared your website in my social networks!

    • admin 2018年11月26日在下午9:04

      🙂

  • Iron ThundeR 2018年12月14日在下午6:22

    Wonderful beat ! I wish to apprentice while you amend your web site, how could i subscribe for a blog site?
    The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast
    provided bright clear concept

    • admin 2018年12月17日在上午9:55

      🙂

  • 3dcgstore 3d models 2018年12月17日在上午12:32

    Aw, this was a very nice post. Taking the time and actual effort to produce a top notch article… but what can I say… I hesitate
    a whole lot and don’t manage to get nearly anything done.

    • admin 2018年12月17日在上午9:55

      🙂

  • Good day! This is my 1st comment here so I just wanted to give a
    quick shout out and tell you I truly enjoy reading
    through your articles. Can you suggest any other blogs/websites/forums that cover the
    same topics? Thank you so much!

    • admin 2018年12月17日在上午9:55

      🙂

  • vintage house restaurant 2018年12月18日在上午1:31

    Someone necessarily help to make severely posts I would state.
    This is the first time I frequented your web page
    and to this point? I amazed with the research you made to make this actual submit
    incredible. Wonderful task!

    • admin 2018年12月19日在下午6:35

      🙂

  • sewa mobil probolinggo murah 2018年12月24日在下午8:56

    It’s an amazing paragraph in favor of all the online users;
    they will obtain advantage from it I am sure.

    • admin 2018年12月24日在下午8:58

      :)

  • Http://crescentmoonhky.com 2018年12月25日在上午11:43

    you’re really a good webmaster. The site loading velocity is amazing.

    It sort of feels that you are doing any distinctive trick.
    In addition, The contents are masterpiece. you’ve performed a great task on this topic!

    • admin 2018年12月25日在下午2:00

      🙂

  • Highland AvenUe Restaurant 2018年12月25日在下午5:05

    Someone necessarily lend a hand to make critically articles I would state.
    This is the first time I frequented your website page
    and thus far? I surprised with the analysis you made to create this particular submit incredible.
    Excellent process!

    • admin 2018年12月25日在下午9:23

      🙂

  • how to seo 2018年12月27日在上午6:18

    I used to be suggested this web site by way of my cousin. I’m not certain whether this publish is written via
    him as nobody else recognize such targeted approximately my
    problem. You are incredible! Thank you!

    • admin 2018年12月27日在上午9:38

      🙂

  • Kill 2018年12月27日在下午2:54

    Ahaa, its good conversation about this paragraph at this place at this
    website, I have read all that, so at this time me also commenting here.
    Hi, I do think this is a great site. I stumbledupon it
    😉 I’m going to return yet again since I bookmarked it.
    Money and freedom is the greatest way to change, may you be rich and continue to help others.

    I simply could not leave your web site before suggesting that I
    really loved the standard info a person supply in your guests?
    Is going to be back incessantly in order to inspect new posts http://foxnews.org

  • diners drive ins and dives orlando 2018年12月27日在下午3:02

    There is certainly a lot to learn about this issue.
    I like all of the points you have made.

    • admin 2018年12月27日在下午4:21

      thank you

  • hello there and thank you for your info – I’ve definitely picked up anything new from right here.
    I did however expertise several technical issues using this site, as I experienced to reload the web site a
    lot of times previous to I could get it to load correctly.
    I had been wondering if your web host is OK?
    Not that I am complaining, but sluggish loading instances times will
    very frequently affect your placement in google
    and could damage your quality score if ads and marketing with Adwords.
    Anyway I am adding this RSS to my email and could look out
    for a lot more of your respective exciting content.
    Ensure that you update this again soon.

  • Big Daddy's Orlando 2018年12月29日在下午7:58

    You have made some decent points there. I checked on the internet for additional information about the issue and found most people will go along with your
    views on this web site.

  • keonhacai 2018年12月30日在上午5:06

    Free PC choices to Recycle and Phatmatik Pro:Loopdrive3 VSTABS.

    “Because you happen to be here reading this article flash games report now as of this particular point in time; what you have is “The first movers advantage” by yourself to consider a their hands on now. These art reproductions of paintings printed on canvas sheets or paper and then framed and hung on walls.

  • https://www.w88top.com/?affiliateid=24645 2018年12月30日在下午11:27

    The great thing concerning this DVD is that you may perform
    dance exercises anytime, without a partner. They will shun jobs its keep is not any advantage of the community
    involved. These art reproductions of paintings printed on canvas sheets or paper after which framed and hung on walls.

  • pesonabromo.com 2019年1月1日在上午3:25

    Inspiring story there. What occurred after?
    Good luck!

  • Jeffery 2019年1月1日在上午9:01

    Each beauty obtainable in Fortnite Battle Royale.

  • wireless wifi doorbell 2019年1月1日在下午2:15

    Way cool! Some very valid points! I appreciate you writing this post and
    the rest of the site is very good.

    • admin 2019年1月1日在下午9:12

      :)

  • property for sale in calahonda 2019年1月6日在上午2:05

    I like reading a post that can make people think.

    Also, thanks for allowing for me to comment!

  • Choices Free Keys 2019年1月12日在下午11:31

    Hola! I’ve been following your website for a while now and finally got the courage to go ahead and give you
    a shout out from Atascocita Texas! Just wanted to tell you keep up the excellent job!

    • admin 2019年1月13日在下午5:07

      :)

  • buca escort 2019年1月15日在下午2:07

    Keep on working, great job! http://organikyumurtaizmir.com

  • Choices Stories You Play generator 2019年1月16日在上午9:00

    This post offers clear idea designed for the new viewers
    of blogging, that really how to do running a blog.

  • camera ip wifi 2019年1月19日在上午2:36

    Spot on with this write-up, I absolutely believe this web site needs a great deal more attention. I’ll probably be back again to see more, thanks
    for the info!

    • admin 2019年1月19日在上午7:25

      thank you

  • teste cs 2019年1月23日在上午6:41

    Just a smiling visitor here to share the love (:, btw outstanding design and style.

    • admin 2019年1月26日在上午8:37

      🙂

  • cat hat 2019年2月28日在上午7:03

    Great web site you have here.. It’s hard to find good quality writing like yours these days.
    I seriously appreciate individuals like you!
    Take care!!

    • admin 2019年3月5日在上午9:13

      🙂

  • Cornelius 2019年3月1日在下午11:08

    Hello colleagues, how is all, and what you would like to say concerning
    this article, in mmy view its truly amazing designed for me.

    • admin 2019年3月5日在上午9:13

      🙂

  • cat hat 2019年3月8日在下午10:36

    I wanted to thank you a lot more for this amazing blog you have
    made here. It truly is full of useful tips for those who are
    definitely interested in this specific subject, particularly this very
    post. You really are all so sweet as well as thoughtful of others and reading your website posts is a
    wonderful delight with me. And such a generous surprise!

    Ben and I will certainly have excitement making use of
    your guidelines in what we should instead do next week.
    Our listing is a kilometer long so your tips will certainly be put to
    great use.

    • admin 2019年3月9日在下午4:51

      :)

  • Keto Rev Diet 2019年3月25日在上午5:19

    I know this if off topic but I’m looking into starting my own weblog and was
    wondering what all is required to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web smart so I’m not 100% positive. Any recommendations
    or advice would be greatly appreciated. Thank you

    • admin 2019年3月25日在上午9:37

      :)

发表评论

电子邮件地址不会被公开。 必填项已用*标注