Learning Java 3 – Threads and Synchronization

13
Overview Overview Threads Synchronization of Threads

description

Basic introduction to threads and synchronization in Java.

Transcript of Learning Java 3 – Threads and Synchronization

Page 1: Learning Java 3 – Threads and Synchronization

OverviewOverview• Threads• Synchronization of Threads

Page 2: Learning Java 3 – Threads and Synchronization

ThreadsThreads

• Everything up to now has been single processing: only one thing was executing at once

• Threads allow multiple things to execute simultaneously

• Most of what you need is in the Thread class

Page 3: Learning Java 3 – Threads and Synchronization

How to Make a How to Make a ThreadThread

• You need to make a public void run() function

• Two options– Class that implements Runnable– Class that extends Thread

• Anonymous inner class

• t = new Thread(Runnable r);• t = new MyThread();

Page 4: Learning Java 3 – Threads and Synchronization

Starting/StoppingStarting/Stopping

• Say we have a Thread t• t.start() – starts executing the

Thread’s run()• t.interrupt() – interrupts a Thread• t.join() – waits for Thread to die

Page 5: Learning Java 3 – Threads and Synchronization

ExampleExample

Thread t1 = new Thread(task1);Thread t2 = new Thread(task2);t1.start(); t2.start();t1.join(); t2.join();

Page 6: Learning Java 3 – Threads and Synchronization

Useful Thread Useful Thread MethodsMethods

• Thead.sleep(long millis[, int nanos]);– Causes current executing Thread to sleep

• Thread.yield();– Causes current executing Thread to be put back

on the ready list

Page 7: Learning Java 3 – Threads and Synchronization

Anonymous Inner Anonymous Inner ClassesClasses

• Quick hack to start a new Thread• Inner classes are bound to an instance of

the enclosing class (so can access its variables)

• Be careful with them

Thread t1 = new Thread() {public void run() {

// Do stuff} };t1.start();

Page 8: Learning Java 3 – Threads and Synchronization

Clobbering Time!Clobbering Time!

• So now we have multiple Threads going at once, but they can trample each other’s feet– Writing to the same variable at the same time– Reading and writing at the same time where order

matters

• Some objects are inherently thread-safe (or “synchronized”)– Vector, Hashtable,

Collections.synchronizedList(List l)

• Synchronization is the key

Page 9: Learning Java 3 – Threads and Synchronization

LocksLocks

• Locks are the primitive for doing synchronization in Java

• Every Object is a lock• Two methods that have code that is

synchronized on the same lock (object) cannot execute that code at the same time

Page 10: Learning Java 3 – Threads and Synchronization

ExampleExample

ArrayList<Integer> list = new ArrayList<Integer>();//…synchronized (list){

list.add(4);}

Page 11: Learning Java 3 – Threads and Synchronization

Synchronized Synchronized methodsmethods

• If an method is synchronized, then the entire code is wrapped in an implicit synchronized (this) { … }

• They will all be synchronized to their instance

• Only one synchronized method of an instance of an object can be running at one time

Page 12: Learning Java 3 – Threads and Synchronization

Waiting, NotifyingWaiting, Notifying• Well, what if I am waiting for something, but it may be

a while?• Must hold the lock of the Object you are waiting /

notifying on (which will be released and reacquired as necessary)

Object bufferFull = new Object();//… the rest should be synchronized on buffer

while (buffer.size() == 10) arrayFull.wait();

//…// notify one threadbuffer.remove();arrayFull.notify();

// or notify everyone!arrayFull.notifyAll();

Page 13: Learning Java 3 – Threads and Synchronization

Advanced Advanced SynchronizationSynchronization

• Java 1.5 adds many shiny new synchronization mechanisms (java.util.concurrent.*)

• Lock provides non-blocking access to code– ReentrantLock

• Condition provides an implementation of condition variables– Associated with a Lock

• Semaphore• AtomicInteger, etc