16. concurrency (thread) it explains how to write applications that perform multiple tasks...

57
16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously.

Upload: ross-charles

Post on 19-Jan-2016

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

16. Concurrency (Thread)

It explains how to write applications that perform multiple tasks simultaneously.

Page 2: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Concurrency

Computer users take it for granted that their systems can do more than one thing at a time.

They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must

simultaneously read the digital audio off the network, decompress it, manage playback, and update its display.

Even the word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display.

Software that can do such things is known as concurrent software.

Page 3: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Processes and Threads

In concurrent programming, there are two basic units of execution: processes and threads.

In the Java programming language, concurrent programming is mostly concerned with threads.

However, processes are also important. A computer system normally has many active processes and threads.

This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment.

Processing time for a single core is shared among processes and threads through an OS feature called time slicing.

Page 4: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class ProcessTest{public static void main(String[] args) throws Exception {

Runtime run = Runtime.getRuntime();Process calc = null;Process exploer = null;try {

calc = run.exec( "calc.exe" );} catch ( Exception ce ) {

System.out.println( "Calcurator run fail " + ce.toString() );}try{

exploer = run.exec( "C:/Program Files/Internet Explorer/IEXPLORE.EXE" );//exploer = run.exec( "C:/Program Files/Internet Explorer/IEXPLORE.EXE www.empas.com" );} catch (Exception ie) {

System.out.println( "Internet Exploer run fail" + ie.toString() );}

int end = calc.waitFor();System.out.println( " 계산기 종료 " + end );

System.out.println( " 계산기 종료상태 = " + calc.exitValue() );}

}

Page 5: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Process

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time

resources; in particular, each process has its own memory space. Processes are often seen as synonymous with programs or

applications. However, what the user sees as a single application may in fact

be a set of cooperating processes. To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets.

IPC is used not just for communication between processes on the same system, but processes on different systems.

Multiprocess applications are beyond the scope of this lesson.

Page 6: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Threads

Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment,

but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process — every process has at least one.

Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Multithreaded execution is an essential feature of the Java platform.

Page 7: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Every application has at least one thread — or several, if you count "system" threads that do things like memory management and signal handling.

But from the application programmer's point of view, you start with just one thread, called the main thread.

This thread has the ability to create additional threads, as we'll demonstrate in the next section.

Page 8: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Thread States: Life Cycle of a Thread

Thread states new state

New thread begins its life cycle in the new state Remains in this state until program starts the thread, placing it in the

runnable state

runnable state A thread in this state is executing its task

waiting state A thread transitions to this state to wait for another thread to perform

a task

Page 9: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Thread states timed waiting state

A thread enters this state to wait for another thread or for an amount of time to elapse

A thread in this state returns to the runnable state when it is signaled by another thread or when the timed interval expires

terminated state A runnable thread enters this state when it completes its task

Page 10: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Page 11: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

1. Thread Objects

Each thread is associated with an instance of the class Thread. There are two basic strategies for using Thread objects to create a concurrent application.

To directly control thread creation and management, simply instantiate Thread each time the application needs to initiate an asynchronous task.

To abstract thread management from the rest of your application, pass the application's tasks to an executor.

This section documents the use of Thread objects. Executors are discussed with other high-level concurrency objects.

Page 12: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

1.1 Defining and Starting a Thread

An application that creates an instance of Thread must provide the code that will run in that thread.

There are two ways to do this: 1. implements Runnable

2. extends Thread

Page 13: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

1.2 Provide a Runnable object.

The Runnable interface defines a single method, run, meant to contain the code executed in the thread.

The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class HelloRunnable implements Runnable {

public void run() { System.out.println("Hello from a thread!"); }

public static void main(String args[]) { (new Thread(new HelloRunnable())).start() ; }}

Page 14: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class RunnableTest implements Runnable {public void printNumber() {

for( int i=1 ; i<=10 ; i++ ) {System.out.println( "number = " + i );}}

// Runnable interface, run() method overridingpublic void run() {

printNumber();}public static void main( String[] args ) {

RunnableTest tt = new RunnableTest();Thread t = new Thread( tt ); t.start();System.out.println( "--------> main thread end" );

}}

public class RunnableTest implements Runnable {public void printNumber() {

for( int i=1 ; i<=10 ; i++ ) {System.out.println( "number = " + i );}}

// Runnable interface, run() method overridingpublic void run() {

printNumber();}public static void main( String[] args ) {

RunnableTest tt = new RunnableTest();Thread t = new Thread( tt ); t.start();System.out.println( "--------> main thread end" );

}}

Page 15: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Operating system’s internal view of Java’s runnable state.

Operating system view of runnable state ready state

A thread in this state is not waiting for another thread, but is waiting for the operating system to assign the thread a processor

running state A thread in this state currently has a processor and is executing

A thread in the running state often executes for a small amount of processor time called a time slice or quantum before transitioning back to the ready state

Page 16: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Subclass Thread.

The Thread class itself implements Runnable, though its run method does nothing.

An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

public class HelloThread extends Thread {

public void run() { System.out.println("Hello from a thread!"); }

public static void main(String args[]) { (new HelloThread()).start(); }}

Notice that both examples invoke Thread.start in order to start the new thread.

Page 17: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class ThreadTest extends Thread {public void printNumber() {

for( int i=1 ; i<=20 ; i++ ) {System.out.println( "number = " + i );

}} // Runnable interface, run() method overridingpublic void run() {

printNumber();}public static void main( String[] args ) {

ThreadTest tt = new ThreadTest();tt.start();System.out.println( "--------> main thread

end" );}}

public class ThreadTest extends Thread {public void printNumber() {

for( int i=1 ; i<=20 ; i++ ) {System.out.println( "number = " + i );

}} // Runnable interface, run() method overridingpublic void run() {

printNumber();}public static void main( String[] args ) {

ThreadTest tt = new ThreadTest();tt.start();System.out.println( "--------> main thread

end" );}}

Page 18: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Tread Test tt=new ThreadTest()

tt.start();run()

printNumber() System.out.println();

End End

Page 19: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class ThreadEnd extends Thread {

public void run() {

for( int i=1 ; i<=20 ; i++ ) {

System.out.println( "run number = " + i );

}

}

public static void main( String[] args ) {

ThreadTest tt = new ThreadTest();

tt.start();

for( int i=101 ; i<=120 ; i++ ) {

System.out.println( "-------> main number = " + i );

}

}

}

public class ThreadEnd extends Thread {

public void run() {

for( int i=1 ; i<=20 ; i++ ) {

System.out.println( "run number = " + i );

}

}

public static void main( String[] args ) {

ThreadTest tt = new ThreadTest();

tt.start();

for( int i=101 ; i<=120 ; i++ ) {

System.out.println( "-------> main number = " + i );

}

}

}

Page 20: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Which of these idioms should you use? The first idiom, which employs a Runnable object, is more

general, because the Runnable object can subclass a class other than Thread.

The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread.

This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task.

Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.

Page 21: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

The Thread class defines a number of methods useful for thread management.

These include static methods, which provide information about, or affect the status of, the thread invoking the method.

The other methods are invoked from other threads involved in managing the thread and Thread object.

We'll examine some of these methods in the following sections.

Page 22: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class ThreadLife implements Runnable{

public void run() {

for( int i=1 ; i<21 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " number = " + i );

}

}

public static void main( String[] args ) {

ThreadLife tl = new ThreadLife();

Thread first = new Thread( tl, "first" );

Thread second = new Thread( tl, "second" );

Thread third = new Thread( tl, "third" );

second.start();

first.start();

third.start();

}}

public class ThreadLife implements Runnable{

public void run() {

for( int i=1 ; i<21 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " number = " + i );

}

}

public static void main( String[] args ) {

ThreadLife tl = new ThreadLife();

Thread first = new Thread( tl, "first" );

Thread second = new Thread( tl, "second" );

Thread third = new Thread( tl, "third" );

second.start();

first.start();

third.start();

}}

Page 23: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Runnable

Block

Running Dead

first

secondthird

Runnable

Block

Running Deadfirstsecond

third

Page 24: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Thread Priority

MAX_PRIORITY : 10

MIN_PRIORITY : 1

main thread priority : 5

Page 25: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class ThreadPriority implements Runnable{

public void run() {

for( int i=1 ; i<21 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " number = " + i );

}}

public static void main( String[] args ) {

ThreadPriority tl = new ThreadPriority();

Thread first = new Thread( tl, "first" );

Thread second = new Thread( tl, "second" );

Thread third = new Thread( tl, "third" );

System.out.println( "first priority = " + first.getPriority() );

System.out.println( "second priority = " + second.getPriority() );

System.out.println( "third priority = " + third.getPriority() );

System.out.println( Thread.currentThread() + " priority = " + Thread.currentThread().getPriority() );

}}

public class ThreadPriority implements Runnable{

public void run() {

for( int i=1 ; i<21 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " number = " + i );

}}

public static void main( String[] args ) {

ThreadPriority tl = new ThreadPriority();

Thread first = new Thread( tl, "first" );

Thread second = new Thread( tl, "second" );

Thread third = new Thread( tl, "third" );

System.out.println( "first priority = " + first.getPriority() );

System.out.println( "second priority = " + second.getPriority() );

System.out.println( "third priority = " + third.getPriority() );

System.out.println( Thread.currentThread() + " priority = " + Thread.currentThread().getPriority() );

}}

Page 26: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class ThreadPriorityControl implements Runnable {

public void run() {

for( int i=1 ; i<11 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " number = " + i );

}}

public static void main( String[] args ) {

ThreadPriorityControl tl = new ThreadPriorityControl();

Thread first = new Thread( tl, "first" );

first.setPriority( Thread.MIN_PRIORITY );

System.out.println( "first priority = " + first.getPriority() );

Thread second = new Thread( tl, "second" );

second.setPriority( Thread.MAX_PRIORITY );

System.out.println( "second priority = " + second.getPriority() );

Thread third = new Thread( tl, "third" );

System.out.println( "third priority = " + third.getPriority() );

first.start();

second.start();

third.start(); }}

public class ThreadPriorityControl implements Runnable {

public void run() {

for( int i=1 ; i<11 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " number = " + i );

}}

public static void main( String[] args ) {

ThreadPriorityControl tl = new ThreadPriorityControl();

Thread first = new Thread( tl, "first" );

first.setPriority( Thread.MIN_PRIORITY );

System.out.println( "first priority = " + first.getPriority() );

Thread second = new Thread( tl, "second" );

second.setPriority( Thread.MAX_PRIORITY );

System.out.println( "second priority = " + second.getPriority() );

Thread third = new Thread( tl, "third" );

System.out.println( "third priority = " + third.getPriority() );

first.start();

second.start();

third.start(); }}

Page 27: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Thread scheduling

Thread.sleep causes the current thread to suspend execution for a specified period.

Runnable

Block

Running

yield()yield()sleep()sleep()

join()join()

* resume(), suspend(), stop() -- > deprecated

Page 28: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public static void sleep(long millis) throws InterruptedException Causes the currently executing thread to sleep (temporarily cease

execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

Parameters: millis - the length of time to sleep in milliseconds.

Throws: InterruptedException - if another thread has interrupted the current thread. The

interrupted status of the current thread is cleared when this exception is thrown.

Page 29: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public static void sleep(long millis, int nanos) throws InterruptedException Causes the currently executing thread to sleep (cease execution)

for the specified number of milliseconds plus the specified number of nanoseconds. The thread does not lose ownership of any monitors.

Parameters: millis - the length of time to sleep in milliseconds. nanos - 0-999999 additional nanoseconds to sleep.

Throws: IllegalArgumentException - if the value of millis is negative or the value of

nanos is not in the range 0-999999. InterruptedException - if another thread has interrupted the current thread. The

interrupted status of the current thread is cleared when this exception is thrown.

Page 30: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public static void yield() Causes the currently executing thread object to temporarily pause

and allow other threads to execute.

join() Method

Page 31: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

import java.util.Date;

public class ThreadSleep implements Runnable { public void run() { for( int i=1 ; i<50 ; i++ ) { System.out.println( Thread.currentThread().getName() + " : " + i + " : " + new Date().toString() );

try {Thread.sleep( 1000);

} catch ( InterruptedException ie ) {System.out.println( ie.toString() );

}}}

public static void main( String[] args ) {ThreadSleep ts = new ThreadSleep();

Thread first = new Thread( ts, "first" );Thread second = new Thread( ts, "second" );

first.start();second.start();

}}

Page 32: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Runnable

Block

Runningfirstsecond

Runnable

Block

Running

first

second

Sleep(1000)

Runnable

Block

Running

first

secondSleep(1000)

Page 33: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

import java.util.*;

public class ThreadYield implements Runnable {public void run() {

for( int i=1 ; i<50 ; i++ ) { System.out.println( Thread.currentThread().getName() + " : " + i);

Thread.yield();}

}

public static void main( String[] args ) {ThreadYield ty = new ThreadYield();

Thread first = new Thread( ty, "first" );// first.setPriority( Thread.MAX_PRIORITY );Thread second = new Thread( ty, "second" );first.start();second.start();

}}

Page 34: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

import java.util.*;public class ThreadYield2 implements Runnable {

public void run() {for( int i=1 ; i<100 ; i++ ) {System.out.println( Thread.currentThread().getName() + " : " + i + " : " + new Date().toString() );

Thread.yield();}

}

public static void main( String[] args ) {ThreadYield2 ts = new ThreadYield2();

Thread first = new Thread( ts, "first" );

//first.setPriority( Thread.MAX_PRIORITY );

Thread second = new Thread( ts, "second" );

first.start();second.start();

}}

Page 35: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

import java.util.*;

public class ThreadJoin implements Runnable {

public void run() {

for( int i=1 ; i<10 ; i++ ) {

System.out.println( Thread.currentThread().getName() + " : " + i);

}}

public static void main( String[] args ) {

ThreadJoin ts = new ThreadJoin();

Thread first = new Thread( ts, "first" );

Thread second = new Thread( ts, "second" );

first.start();

second.start();

try {

first.join();} catch ( InterruptedException ie ) {

System.out.println( ie.toString() );

}

// main thread

System.out.println( "main thread end" );

}}

Page 36: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

1.3 Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution for a specified period.

This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

The sleep method can also be used for pacing, as shown in the example that follows,

and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

Page 37: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond.

However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS.

Also, the sleep period can be terminated by interrupts, as we'll see in a later section.

In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

Page 38: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

The SleepMessages example uses sleep to print messages at four-second intervals:

public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" };

for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); } }}

Page 39: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Notice that main declares that it throws InterruptedException. This is an exception that sleep throws when another thread

interrupts the current thread while sleep is active. Since this application has not defined another thread to cause

the interrupt, it doesn't bother to catch InterruptedException.

Page 40: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

2. Synchronization

Threads communicate primarily by sharing access to fields and the objects reference fields refer to.

This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors.

Page 41: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

The tool needed to prevent these errors is synchronization. Thread Interference describes how errors are introduced when

multiple threads access shared data. Memory Consistency Errors describes errors that result from

inconsistent views of shared memory. Synchronized Methods describes a simple idiom that can

effectively prevent thread interference and memory consistency errors.

Implicit Locks and Synchronization describes a more general synchronization idiom, and describes how synchronization is based on implicit locks.

Atomic Access talks about the general idea of operations that can't be interfered with by other threads.

Page 42: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

2.1 Thread Interference

class Counter { private int c = 0; public void increment( ) { c++; }

public void decrement( ) { c--; }

public int value( ) { return c; }

}

Suppose Thread A invokes increment at about the same time Thread B invokes decrement.

If the initial value of c is 0, their interleaved actions might follow this sequence: Thread A: Retrieve c. Thread B: Retrieve c. Thread A: Increment retrieved value;

result is 1. Thread B: Decrement retrieved value;

result is -1. Thread A: Store result in c; c is now 1. Thread B: Store result in c; c is now -1.

Thread A's result is lost, overwritten by Thread B. This particular interleaving is only one possibility.

Under different circumstances it might be Thread B's result that gets lost, or there could be no error at all. Because they are unpredictable, thread interference bugs can be difficult to detect and fix.

Page 43: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

2.3 Synchronized Methods

The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements.

This section is about synchronized methods. To make a method synchronized, simply add the synchronized

keyword to its declaration: public class SynchronizedCounter { private int c = 0;

public synchronized void increment() { c++; }

public synchronized void decrement() { c--; }

public synchronized int value() { return c; }}

Page 44: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects: First, it is not possible for two invocations of synchronized

methods on the same object to interleave. When one thread is executing a synchronized method for an object,

all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.

This guarantees that changes to the state of the object are visible to all threads.

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error.

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors

Page 45: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Synchronized Statements

Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods.

public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name);}

Page 46: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Synchronized statements are also useful for improving concurrency with fine-grained synchronization.

Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together.

All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking.

Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

Page 47: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class MsLunch { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object();

public void inc1() { synchronized(lock1) { c1++; } }

public void inc2() { synchronized(lock2) { c2++; } }}

Use this idiom with extreme care.

You must be absolutely sure that it really is safe to interleave access of the affected fields.

Page 48: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Thread Interaction

The Object class has three methods, wait(), notify(), and notifyAll() that help threads communicate

wait(), notify(), and notifyAll() must be called from within a synchronizedcontext! A thread can't invoke a wait or notify method on an object unless it ownsthat object's lock.

Runnable

wait pool

Runningrun()

wait()

notify()notifyAll()lock pool

lock flag

Page 49: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public final void notify() Wakes up a single thread that is waiting on this object's monitor. If any

threads are waiting on this object, one of them is chosen to be awakened. This method should only be called by a thread that is the owner of this

object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

• By executing a synchronized instance method of that object.

• By executing the body of a synchronized statement that synchronizes on the object.

• For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

public final void notifyAll() Wakes up all threads that are waiting on this object's monitor. This

method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Page 50: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public final void wait(long timeout) throws InterruptedException Causes current thread to wait until either another thread invokes

the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor. If the current thread is interrupted by another thread while it is

waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

public final void wait(long timeout, int nanos) throws InterruptedException

public final void wait() throws InterruptedException

Page 51: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class Producer implements Runnable {private AutoMachine machine;

public Producer( AutoMachine machine ) {this.machine = machine;

}

public void run() {for( int i=0 ; i<10 ; i++ ) {machine.putDrink( “Drink " + i );System.out.println( "Producer : drink " + i );

try {Thread.sleep(300);

} catch ( Exception e ) {e.printStackTrace();}

}}

}

Page 52: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class Consumer implements Runnable {private AutoMachine machine;

public Consumer( AutoMachine machine ) {this.machine = machine;

}

public void run() {for(int i=0 ; i<10 ; i++ ) {

System.out.println( "Consumer : " + machine.getDrink() );

try {Thread.sleep( 300 );

} catch ( Exception e ) {e.printStackTrace();}

}}

}

Page 53: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

import java.util.Stack;

public class AutoMachine {Stack store = new Stack();

public synchronized String getDrink() {while( store.isEmpty() ) {

try {this.wait();

} catch( Exception e ) {e.printStackTrace();}

}return store.pop().toString();

}

public synchronized void putDrink( String drink ) {

this.notify();store.push( drink );

}}

//Using wait( ) in a Loop

Page 54: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

public class Management {public static void main( String[] args ) {

AutoMachine drink = new AutoMachine();

Producer producer = new Producer( drink );

Consumer consumer = new Consumer( drink );

Thread t1 = new Thread( producer );Thread t2 = new Thread( consumer );

t1.start();t2.start();

}}

Page 55: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Using notifyAll( ) When Many Threads May Be Waitingclass Reader extends Thread {Calculator c;public Reader(Calculator calc) { c = calc; }

public void run() { synchronized(c) { try { System.out.println("Waiting for calculation..."); c.wait(); } catch (InterruptedException e) {} System.out.println("Total is: " + c.total); } }

public static void main(String [] args) { Calculator calculator = new Calculator(); new Reader(calculator).start(); new Reader(calculator).start(); new Reader(calculator).start(); calculator.start(); } }

class Calculator extends Thread { int total;

public void run() { synchronized(this) { for(int i=0;i<100;i++) { total += i;

notifyAll(); } } }

Page 56: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Key Thread Methods

sleep / yield => static method ( ex. Thread.sleep(1000)) start / join => non-static

Page 57: 16. Concurrency (Thread) It explains how to write applications that perform multiple tasks simultaneously

java programming CHOJOCHOJO

Exercise

Study about Multithreading with GUI section 23.10 from book “Java How to Program 6th edition, Deitel, Prentice Hall”

Make a program about multithreading with GUI You are permitted to find the reference on internet,

but you should mention the resources

Deadline 1 week from now: Monday (29 November 2010) ,

send to: [email protected]