learning java 3 – threads and synchronization
DESCRIPTION
Basic introduction to threads and synchronization in Java.TRANSCRIPT
OverviewOverview• Threads• Synchronization of Threads
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
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();
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
ExampleExample
Thread t1 = new Thread(task1);Thread t2 = new Thread(task2);t1.start(); t2.start();t1.join(); t2.join();
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
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();
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
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
ExampleExample
ArrayList<Integer> list = new ArrayList<Integer>();//…synchronized (list){
list.add(4);}
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
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();
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