Java Multi-threaded applet hibernation, pause, and stop

Source: Internet
Author: User
Tags deprecated

Hibernate

?? In Java Multi-threading, you can use the sleep () method to hibernate the currently executing thread for a specified number of milliseconds.
?? The following code allows the main function to hibernate 2000ms, and the last output interval is 2000ms.

public class MyThread extends Thread {    public static void main(String[] args) {        try {            long begin;            long end;            begin = System.currentTimeMillis();            System.out.println("begin = " + begin);            Thread.sleep(2000);            end = System.currentTimeMillis();            System.out.println("end = " + end);            System.out.println("end - begin = " + (end - begin) + "ms");        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

Output Result:

Begin = 1486711105366
End = 1486711107366
End-begin = 2000ms

Pause

?? Although the suspend and resume methods allow threads to pause and reply separately, these two methods have been deprecated because of their drawbacks.

Disadvantages:

    • Exclusive: When using the suspend and resume methods, if used improperly, it is very easy to create a public synchronization object exclusive, so that other threads cannot access the public synchronization objects.
    • Out of sync: When using the suspend and resume methods, it is also easy to cause data to be out of sync due to threads.
Yield method

?? You can use the yield method to pause.
?? The yield () method is used to discard the current CPU resources and give it to other tasks to occupy CPU execution time. But the time to give up is uncertain, it is possible to just give up, and immediately get the CPU time slice.

public class MyThread extends Thread {    @Override    public void run() {        long beginTime = System.currentTimeMillis();        int count = 0;        for (int i = 0; i < 50000000; i++) {            //Thread.yield();            count = count + (i + 1);        }        long endTime = System.currentTimeMillis();        System.out.println("用时: " + (endTime - beginTime) + "ms");    }    public static void main(String[] args) {        MyThread myThread = new MyThread();        myThread.start();    }}

Output Result:

Spents: 21ms

?? After removing the comment//thread.yield ().

Output Result:

Spents: 4471ms

?? As can be seen from the second output, time is significantly longer.

Stop

?? Although stop () can stop a thread, this method is unsafe and is deprecated and should not be used.

Interrupt () method

?? The interrupt () method does not use the same effect as the For+break statement, and immediately stops the loop. Calling the interrupt () method simply marks a stop in the current thread and does not actually stop the thread.

To determine if a thread is a stopped state
    • This.interrupted (): Tests whether the current thread is already in a break state, and performs a static method with the ability to clear the status flag to False.
    • This.isinterrupted (): Tests whether the thread object is already in a broken state, but does not clear the status flag.
public class MyThread extends Thread {    public static void main(String[] args) {        Thread.currentThread().interrupt();        System.out.println("是否停止1? " + Thread.interrupted());        System.out.println("是否停止2? " + Thread.interrupted());        System.out.println("end");    }}

Output Result:

Do you want to stop 1? True
Do you want to stop 2? False
End

public class MyThread extends Thread {    @Override    public void run() {        for (int i = 0; i < 50000; i++) {            System.out.println(i);        }    }    public static void main(String[] args) {        try {            MyThread myThread = new MyThread();            myThread.start();            Thread.sleep(1000);            myThread.interrupt();            System.out.println("是否停止1? " + myThread.isInterrupted());            System.out.println("是否停止2? " + myThread.isInterrupted());            System.out.println("end");        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

Output result (end):

49997
49998
49999
Do you want to stop 1? False
Do you want to stop 2? False
End

A way to stop a thread

?? Add a judgment in run and if it stops, break jumps out of the loop body.

public class MyThread extends Thread {    @Override    public void run() {        for (int i = 0; i < 50000000; i++) {            if (this.interrupted()) {                System.out.println("已经是停止状态了,我要退出了");                break;            }            System.out.println(i);        }    }    public static void main(String[] args) {        try {            MyThread myThread = new MyThread();            myThread.start();            Thread.sleep(1000);            myThread.interrupt();            System.out.println("end");        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

Output result (end):

160560
160561
160562
160563
160564
End
It's already stopped, I'm quitting.

?? Although the above code can stop the thread, it will continue to execute if there is a statement later in the for.
?? Therefore, the following methods can be used to solve.

public class MyThread extends Thread {    @Override    public void run() {        try {            for (int i = 0; i < 50000000; i++) {                if (this.interrupted()) {                    System.out.println("已经是停止状态了,我要退出了");                    throw new InterruptedException();                }                System.out.println(i);            }            System.out.println("for结束");        } catch (InterruptedException e) {            System.out.println("进入run中的catch了");            e.printStackTrace();        }    }    public static void main(String[] args) {        try {            MyThread myThread = new MyThread();            myThread.start();            Thread.sleep(1000);            myThread.interrupt();            System.out.println("end");        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

Output result (end):

152891
152892
152893
152894
End
It's already stopped, I'm quitting.
Into the catch in run.
Java.lang.InterruptedException
At Mythread. Mythread.run (mythread.java:13)

Java Multi-threaded applet hibernation, pause, and stop

Related Article

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.