think in java - concurrency - interruption

why we need interruption?

if run() method blocked, we want to break out of it, we can use Thread.interrupt() to terminate this task.


# interrupt()

set interrupted status. [1] if no below conditions:

If this thread is blocked in an invocation of wait(), join(), sleep(), [1] will be cleared and get InterruptedException.

If this thread is blocked in a I/O operation.

If this thread is blocked while trying to acquire the lock.


# interrupted()

return true if current thread has been interrupted, otherwise false.

clear the [1].

try {
    while (!Thread.interrupted()) {
        // do sth while current thread not be interrupted...
    }
} catch (InterruptedException e) {
    print("Exiting via InterruptedException");
}


# how to interrupt all threads inside Executor?

use shutdownNow(), which will send an interrupt() call to each of the threads it has started.


# how to interrupt particular task inside Executor?

use submit() instead of execute(), then we get Future, then we call cancel() to interrupt the particular task.


# blocking

we have interruptible blocking(sleep block) and uninterruptible blocking(I/O block, synchronized block).


# how to interrupt I/O or synchronized blocking?

The effecive solution is to close the underlying resource on which the task is blocked.


# If one task holds the lock of obj, then it is able to call other synchronized methods within the same object.

public class MultiLock {
	
	public static void main(String[] args) {
		final MultiLock ml = new MultiLock();
		new Thread(new Runnable() {
			@Override
			public void run() {
				ml.med1(10); 
			}
		}).start();
	}
	
	public synchronized void med1(int count) {
		if (count -- > 0) {
			System.out.println("med1 call med2 with count: " + count);
			med2(count);
		}
	}
	
	public synchronized void med2(int count) {
		if (count-- > 0) {
			System.out.println("med2 call med1 with count: " + count);
			med1(count);
		}
	}
}

你可能感兴趣的:(think in java - concurrency - interruption)