Home > Java > javaTutorial > How to solve wait call interruption in java

How to solve wait call interruption in java

WBOY
Release: 2023-04-25 10:34:06
forward
1331 people have browsed it

1. Solution

(1) When using java threads, the wait method will often be used, and if it is interrupted when the wait method is called, the jvm will capture the interruption and Continue to call the wait instruction.

(2) Even if you use the interrupt sending method at this time, no effect will occur.

(3) The wait method needs to be encapsulated, catch the exception, and then stop executing the exception.

2. Example

public static void wait(Object obj) {
        boolean interrupted = true;
        while (interrupted) {
            interrupted = false;
            try {
                obj.wait();
            }
            catch (InterruptedException e) {
                interrupted = true;
            }
        }
    }
 
    public static void wait(Object obj, int timeout) {
        boolean interrupted = true;
        long startTime = System.currentTimeMillis();
        int sleepTimeout = timeout;
 
        while (interrupted) {
            interrupted = false;
            try {
                obj.wait(sleepTimeout);
            }
            catch (InterruptedException e) {
                interrupted = true;
                long now = System.currentTimeMillis();
                sleepTimeout -= now - startTime;
                startTime = now;
                if (sleepTimeout < 0) {
                    interrupted = false;
                }
            }
        }
}
Copy after login

The above is the detailed content of How to solve wait call interruption in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template