- Package – java.util.concurrent
- Concerns two topics – processes & threads
- Processes is based on computer hardware processor (runtime resources)
- Each process has its own memory space
- Threads exist within a process
- Implement Runnable interface and provide code for "run" method
- Subclass the Thread class
- Thread.sleep causes the current thread to pause execution for a specific period (note that neither the Runnable interface is implemented nor the Thread class is extended. Just call Thread.sleep with time)
- Supporting thread interruption
For a thread "A" to interrupt thread "B", thread "B" should be supporting its own interruption (i.e. the thread should be returning immediately when an interruption is received)
Below class supports interruption since immediately the exception is received the thread returns
If a thread continues to run without any InterruptedException then the thread should frequently call interrupt method to check if an interruption is available. If yes then should return immediately. Code snippet is as below.
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}
- To tell thread "A" to resume execution after thread "B" completes (in other words, to tell thread "A" to
B.join(); // within thread "A", we are telling A to join B
Thread interference Thread interference occurs when multiple threads run on 2 operations but act on same data (interleave)
See below sample code
class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }<CONTINUES FROM https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html>




No comments:
Post a Comment