Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Java stops the thread

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Stop () is out of date.

Stop the thread: the run () method ends.

Turn on multi-threaded running, usually the code is a loop structure.

As long as you control the loop, you can let run () end, which ends the thread.

Class StopThread implements Runnable {private boolean flag = true; @ Override public void run () {while (flag) {System.out.println (Thread.currentThread (). GetName () + ".run");} public void changeFlag () {flag = false;}} public class StopThreadDemo {public static void main (String [] args) {StopThread st = new StopThread () Thread T1 = new Thread (st); Thread T2 = new Thread (st); t1.start (); t2.start (); int num = 0; while (true) {if (num++ = = 60) {st.changeFlag (); break } System.out.println (Thread.currentThread (). GetName () + "." + num);}

Special case: when the thread is frozen, the tag will not be read, so the thread will not end.

When there is no specified way to restore the frozen thread to the running state, it is necessary to clear the freeze and force the thread to return to the running state, so that the flag can be operated to let the thread end.

This method is provided in the Thread class: interrupt ()

Class StopThread implements Runnable {private boolean flag = true; @ Override public synchronized void run () {while (flag) {try {wait ();} catch (InterruptedException e) {System.out.println (Thread.currentThread (). GetName () + ".exception"); flag = false } System.out.println (Thread.currentThread (). GetName () + ".. run");} public void changeFlag () {flag = false;}} public class StopThreadDemo {public static void main (String [] args) {StopThread st = new StopThread (); Thread T1 = new Thread (st); Thread T2 = new Thread (st); t1.start () T2.start (); int num = 0; while (true) {if (num++ = = 60) {/ / st.changeFlag (); t1.interrupt (); t2.interrupt (); break } System.out.println (Thread.currentThread (). GetName () + "." + num);} System.out.println ("over");}}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report