Thread Break in Java

Source: Internet
Author: User

In Java, you can use the interrupt () function for thread breaks. Although this function cannot terminate a thread's run, it can change the state of the thread to True

That is: The value of isinterrupted () returns True

Note: When the function calls a thread that has already been blocked, the blocked thread will receive a Interruptedexception exception. That is, the current thread can terminate.

For example:

Package Testthread.threadsynchronized;public class Testwaitall {public static void main (string[] args) {//Create thread object Test1 te St1 = new Test1 ();//create threads thread t = new Thread (test1, "Thread 1"); thread T1 = new Thread (test1, "Thread 2"); Thread t2 = new Thread (test1, "Thread 3"); thread t3 = new Thread (test1, "Thread 4");//This is the wake thread Test2 test2 = new Test2 (test1, "Wake thread"); T.start (); T1.start (); T2.start (); t2.i Nterrupt ();//Interrupt thread T3.start (); try {thread.sleep ();} catch (Interruptedexception e) {e.printstacktrace ();} Start Wakeup thread Test2.start ();}} Class Test1 implements Runnable {public void run () {synchronized (this) {//) exception try {interrupt () occurs when a blocked thread calls this.wait; System.out.println (Thread.CurrentThread (). GetName () + ": I'm not interrupted, I can do it! ");} catch (Interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName () + ": Interrupted! ");}}}} /** * @author CHAI015 generate wake-up class */class Test2 extends Thread {/** * Test1 for Wake-up object name is the thread name */private Test1 test1; String name;/** * @param test1 Wake-Up Object * @param name wake-up name */public Test2 (Test1 test1, String Name) {super (name); this.name = Name;this.test1 = test1;} public void Run () {synchronized (test1) {test1.notifyall ();//The operation to wake all threads for the current object System.out.println ( Thread.CurrentThread (). GetName () + ": Wake-up thread execution succeeded! ");}}}

The result of the operation is:

Thread Break 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.