JAVA CONCURRENCY Creating Threads Two ways to create













![An Example of Monitor public class Tester { public static void main(String[] args) { An Example of Monitor public class Tester { public static void main(String[] args) {](https://slidetodoc.com/presentation_image_h2/8599f6944ade91ff76af3108e6c0734e/image-14.jpg)






- Slides: 20

JAVA CONCURRENCY

Creating Threads Two ways to create threads Subclassing Thread class My. Thread extends Thread { public void run() { // do the work } } public class Using. Threads { public void some. Function() { My. Thread t = new My. Thread(); t. start(); } } Implementing Runnable class My. Runnable implements Runnable { public void run() { // do the work } } public class Using. Threads { public void some. Function() { Thread t = new Thread(new My. Runnable()); t. start(); } }

Threads Basics Thread@start() starts a new thread which executes the run() method A thread stops when run() completes A Thread object can only be started once Don’t override start() Methods of a Thread/Runnable can be called just like method of regular objects.

Threads Basics start() can only be called once on a Thread. class My. Thread extends Thread { public void run() { // do the work } } public class Using. Threads { public void some. Function() { My. Thread t = new My. Thread(); t. start(); //Illegal. Thread. State. Exception } }

Threads Basics Main() { Thread t = new My. Thread(); t. start(); t. run(); // do work 1 main thread new thread main thread run() main() None main() start() new thread

Threads Basics main() main thread new thread class My. Thread extends Thread { public void run() { // work 1 start() method(); } public void method() { // work 2 } } class Main. Thread { void main(. . . ) { My. Thread t = new My. Thread(); t. start(); t. join(); t. method() called by t. run() & t. method(); run() method() main() runs in the thread of the caller called by run() run in its own thread

Threads Basics one thread new thread start() method() Any thread or any method can create and start a new Thread run() function() class My. Thread extends Thread { public void run() { // work 1 function(); } public void method() { // work 2 } } class Other. Thread extends Thread { void function(. . . ) { Thread t = new My. Thread(); t. start();

Threads Basics - join One thread can wait for another thread to complete class My. Thread extends Thread { public void run() { // work 1 function(); } } class Main. Thread { void main(. . . ) { Thread t = new My. Thread(); t. start(); t. join(); // wait until t completes // to be executed after t completes

Monitor in Java Each instance of Object has two types of operations Synchronized operations Normal operations Consider all synchronized operations together as a room Only one thread can enter the room All other threads which want to enter must wait One of the waiting threads is chosen to enter when the current thread exits the room Normal operations can be called and executed in any thread at any time. They may be called by the thread in the room They may be called by any thread at any place They may be executed concurrently or in any arbitrary order

Monitor in Java t 3 Thread ti No thread in the room, the door is open Thread ti op 1 op 2 Thread ti is in the room, the door is closed/locked Thread ti is in the room, t 1, t 2, and t 3 must wait until ti is out of the room t 2 t 1

An Example of Monitor Thread. Safe. Stack and Thread. Unsafe. Stack are identical except push, pop, and size in Thread. Safe. Stack are synchronized Thread. Safe. Stack is thread-safe – no race condition problem when accessed by multiple threads concurrently Only one thread can executed push or pop at a time, not concurrently. Thread. Unsafe. Stack is not thread-safe. Can you see that the size variable may be incremented only by one after two threads have pushed two items into the stack?

An Example of Monitor class Thread. Unsafe. Stack { private Array. List<Integer> stack; private int size = 0; public Thread. Unsafe. Stack() { stack = new Array. List<Integer>(); } public void push(Integer item) { stack. add(item); size++; } public Integer pop() { Integer top = null; if (size()>0) { top = stack. remove(0); size--; } return top; } public int size() { return size; } }

An Example of Monitor class Thread. Safe. Stack { private Array. List<Integer> stack; private int size = 0; public Thread. Safe. Stack() { stack = new Array. List<Integer>(); } public synchronized void push(Integer item) { stack. add(item); size++; } public synchronized Integer pop() { Integer top = null; if (size()>0) { top = stack. remove(0); size--; } return top; } public synchronized int size() { return size; } }
![An Example of Monitor public class Tester public static void mainString args An Example of Monitor public class Tester { public static void main(String[] args) {](https://slidetodoc.com/presentation_image_h2/8599f6944ade91ff76af3108e6c0734e/image-14.jpg)
An Example of Monitor public class Tester { public static void main(String[] args) { Thread. Safe. Stack stack = new Thread. Safe. Stack(); Thread t 1 = new My. Thread(stack, 100); Thread t 2 = new My. Thread(stack, 200); t 1. start(); t 2. start(); try { t 1. join(); } catch (Interrupted. Exception e) {} try { t 2. join(); } catch (Interrupted. Exception e) {} } } class My. Thread extends Thread { private Thread. Safe. Stack stack; private int start. Val; public My. Thread(Thread. Safe. Stack stack, int start. Val) { this. stack = stack; this. start. Val = start. Val; } public void run() { for (int i = 0; i < 10; i++) { stack. push(i + start. Val); System. out. println("Pushed in: " + start. Val); try { sleep(1000); } catch (Interrupted. Exception e) {} } int value; for (int i = 0; i < 10; i++) { value = stack. pop(); System. out. println("Popped out: " + value); System. out. println(value); try { sleep(1000); } catch (Interrupted. Exception e) {} }

Synchronized Blocks Java allows program blocks to form a monitor by synchronizing on the object. Accesses to counter 1 class Sync. Blocks { Object monitor 1 = new Object(); Object monitor 2 = new Object(); private int counter 1; private int counter 2; are synchronized on monitor 1 Accesses to counter 2 are synchronized on monitor Since Object is the superclass of every class, so you can synchronize on any object of any class. } public void inc. Counter 1() synchronized(monitor 1) counter 1++; } } public void dec. Counter 1() synchronized(monitor 1) counter 1++; } } public void inc. Counter 2() synchronized(monitor 2) counter 2++; } } public void dec. Counter 2() synchronized(monitor 2) counter 2++; } } { { { {

Synchronized Blocks monitor 1 inc. Counter 1 dec. Counter 1 No one is executing inc. Counter 1() and dec. Counter 1(), the door is open monitor 2 Thread ti inc. Counter 2 dec. Counter 2 Thread ti is executing inc. Counter 2(), t 1, t 2, and t 3 must wait until ti completes the operation. t 3 t 2 t 1

Wait and notify Each monitor in Java has one implicit Condition threads can wait on by calling Object. wait() When the thread calls wait(), it opens the door and puts itself to the waiting list of the Condition. The thread in the room may call Object. notify() to move one thread waiting on the Condition to the waiting list by the door, or Object. notify. All() to move all threads waiting on the Condition to the waiting list by the door. Wait(), notify(), and notify. All() must be called from a synchronized method or block

An Example of Join/Notify class Bounded. Buffer { private int count = 0; private int[] buffer = new int[10]; private int cursor = 0; public synchronized void deposit(Integer item) { // if the buffer is full, wait on Condition while (count >= 10) try { wait(); } catch (Interrupted. Exception e) {}; buffer[cursor] = item; cursor = (cursor + 1) % 10; count++; // if is was empty, notify all waiting threads if (count == 1) notify. All(); } public synchronized int remove() { // if the buffer is empty, wait on Condition while (count == 0) try { wait(); } catch (Interrupted. Exception e) {} int item = buffer[cursor]; cursor = (cursor - 1 + 10) % 10; count--; // if it was full, notify all waiting threads if (count == 9) notify. All(); return item; } }

An Example of Join/Notify tz buffer Thread ti ty deposit() tx Condition remove() t 3 t 2 t 1 Threads tx, ty, tz called remove() on an empty buffer, so they are in the waiting list of the Condition. Thread ti is executing deposit(). When ti calls notify. All(), tx, ty, and tz are moved to the waiting list by the door. When ti leaves deposit(), the door will be open and one of the 6 waiting threads is randomly chosen to enter the room and the door will be closed again.

Looper in Android A worker threads can take a queue of tasks (Runnables) to execute them one at a time.