Terminating a running thread in Java

Source: Internet
Author: User

Question: How do I get a running thread to terminate in Java?

Demo_1:

Class TT implements Runnable {Private Boolean flag = true; @Overridepublic void Run () {int i = 0;while (flag) {SYSTEM.OUT.PR INTLN ("Child Thread:" +i++);}} public void Shutdowm () {flag = false;}} Class Testthread {public static void main (string[] args) {TT TT = new TT (); Thread t = new Thread (TT), T.start (), for (int i = 0, i < 4; i++) {SYSTEM.OUT.PRINTLN ("The main Thread is running:" +i);} SYSTEM.OUT.PRINTLN ("Thread main is void"); Tt.shutdowm ();}}

Demo_2:

Class TT implements Runnable {@Overridepublic void Run () {for (int i = 1; I <= 589; i++) {System.out.println ("Subthread: "+ i);}}} Class Testthread {public static void main (string[] args) {TT TT = new TT (); Thread t = new thread (TT); T.start (); try {t.join ();} catch (Interruptedexception e) {}for (int i = 0; i < 8; i++) {System . Out.println ("Main Thread is running:" +i);}}

Demo_3:

Class TT extends Thread {@Overridepublic void Run () {for (int i = 1; I <= 5; i++) {System.out.println ("Subthread:" + i);} }}class testthread {public static void main (string[] args) {TT TT = new TT (); Tt.start (); Thread dd = new TT ();dd. Start (); for (int i = 0; i < 8; i++) {System.out.println ("main Thread is running:" +i);}}

Operation Result:

Main Thread is running:0
Main Thread is running:1
Main Thread is Running:2
Subthread:1
Subthread:1
Subthread:2
Subthread:2
Main Thread is Running:3
Main Thread is Running:4
Main Thread is Running:5
Main Thread is Running:6
Main Thread is Running:7
Subthread:3
Subthread:4
Subthread:5
Subthread:3
Subthread:4
Subthread:5

Terminating a running thread in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.