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

How to solve wait call interruption in java

WBOY
WBOYforward
2023-04-25 10:34:061242browse

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;
                }
            }
        }
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete