Threads. What Is a Thread? Customizing a Thread's run Method. Understanding Threads. Subclassing Thread and Overriding run. Thread Objects.

Similar documents
Definition: A thread is a single sequential flow of control within a program.

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

7. MULTITHREDED PROGRAMMING

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

CIS233J Java Programming II. Threads

CS 556 Distributed Systems

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

CMSC 132: Object-Oriented Programming II. Threads in Java

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Concurrent Programming

Object Oriented Programming (II-Year CSE II-Sem-R09)

Module - 4 Multi-Threaded Programming

Multithreaded Programming

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction to Java Threads

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Threads Chate Patanothai

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Java s Implementation of Concurrency, and how to use it in our applications.

Java Threads. Thread. Rui Moreira. control within a program. threads. performed concurrently

Multithread Computing

Performance Throughput Utilization of system resources

Java Threads. COMP 585 Noteset #2 1

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Java Threads. Written by John Bell for CS 342, Spring 2018

Multi-threading in Java. Jeff HUANG

Multithreaded Programming

Chapter 32 Multithreading and Parallel Programming

Concurrent Programming using Threads

Threads Questions Important Questions

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Chapter 19 Multithreading

CMSC 330: Organization of Programming Languages

Unit - IV Multi-Threading

COE518 Lecture Notes Week 7 (Oct 17, 2011)

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Java Threads. Introduction to Java Threads

Object Oriented Programming. Week 10 Part 1 Threads

Advanced Concepts of Programming

Animation Part 2: MoveableShape interface & Multithreading

Techniques of Java Programming: Concurrent Programming in Java

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Only one thread can own a specific monitor

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

THREADS AND CONCURRENCY

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Unit III Rupali Sherekar 2017

Unit 5 - Exception Handling & Multithreaded

Contents. 6-1 Copyright (c) N. Afshartous

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Reintroduction to Concurrency

Threads in Java (Deitel & Deitel)

THREADS & CONCURRENCY

CS 159: Parallel Processing

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Threads, Concurrency, and Parallelism

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

CS11 Java. Fall Lecture 7

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Synchronization

Interprocess Communication By: Kaushik Vaghani

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Programming Language Concepts: Lecture 11

G52CON: Concepts of Concurrency

THREADS & CONCURRENCY

Concurrent Computing CSCI 201 Principles of Software Development

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Synchronized Methods of Old Versions of Java

Basics of. Multithreading in Java

CSCD 330 Network Programming

Java Programming Lecture 23

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

CSCD 330 Network Programming

Threads and Parallelism in Java

By: Abhishek Khare (SVIM - INDORE M.P)

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Component-Based Software Engineering

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

CS360 Lecture 12 Multithreading

CS 351 Design of Large Programs Threads and Concurrency

Synchronization in Concurrent Programming. Amit Gupta

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

Multithreading Pearson Education, Inc. All rights reserved.

Transcription:

Threads A thread is a flow of control in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. When a Java Virtual Machine starts up, there is usually a single thread (which typically calls the method named main of some designated class). Threads are given priorities. A high priority thread has preference over a low priority thread. What Is a Thread? A sequential program has a beginning, an execution sequence, and an end. At any given time during the runtime of the program, there is a single point of execution. A single thread also has a beginning, an execution sequence, and an end, and at any given time during the runtime of the thread, there is a single point of execution. However, a thread itself is not a program, it runs within a program. A program may have many threads running at the same time. Definition: A thread is a single sequential flow of control within a program. A thread is sometimes called a lightweight process. As a sequential flow of control, a thread must carve out some of its own resources within a running program. (It must have its own execution stack and program counter for example.) The code running within the thread works only within that context. Thus, execution context is used as a synonym for thread. Understanding Threads You must be able to answer the following questions What code does a thread execute? What states can a thread be in? How does a thread change its state? How does synchronization work? Thread Objects As is everything else, threads in Java are represented as objects. The code that a thread executes is contained in its run() method. There is nothing special about the run method, anyone can call it. To make a thread eligible for running you call its start() method Among the properties of a thread object are: name priority daemon property ThreadGroup state Example public class Throw extends Thread { for ( int i=0; i<10; i++) System.out.println("Count: " + i); System.out.println(getName()); throw new Error("here"); public static void main(string args[]) { Throw ct = new Throw(); ct.setname("another Thread"); ct.start(); throw new Error("there"); >java Throw Exception in thread "main" java.lang.error: there at Throw.main(Throw.java:13) Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Count: 6 Count: 7 Count: 8 Count: 9 Another Thread java.lang.error: here at Throw.run(Throw.java:6) Customizing a Thread's run Method The run method gives a thread something to do. Its code implements the thread's running behavior. It can do anything that can be encoded in Java statements: compute a list of prime's, sort some data, perform some animation. The Thread class implements a generic thread that, by default, does nothing. That is, the implementation of its run method is empty. This is not particularly useful, so the Thread class defines API that lets a Runnable object provide a more interesting run method for a thread. There are two techniques for providing a run method for a thread: Subclassing Thread and Overriding run Implementing the Runnable Interface Subclassing Thread and Overriding run The first way to customize what a thread does when it is running is to subclass Thread (itself a Runnable object) and override its empty run method so that it does something. public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); for (int i = 0; i < 10; i++) { System.out.println(i + " " + getname()); sleep((long)(math.random() * 1000)); catch (InterruptedException e) { System.out.println("DONE! " + getname()); The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor calls the superclass constructor and sets the Thread's name. The next method overrides the run method in Thread. This gives the thread something to do. The TwoThreadsDemo main method creates and starts two SimpleThread threads: one named "Jamaica" and the other named "Fiji".

public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); Output of the TwoThreadsDemo 0 Jamaica 0 Fiji 1 Fiji 1 Jamaica 2 Jamaica 2 Fiji 3 Fiji 3 Jamaica 4 Jamaica 4 Fiji 5 Jamaica 5 Fiji 6 Fiji 6 Jamaica 7 Jamaica 7 Fiji 8 Fiji 9 Fiji 8 Jamaica DONE! Fiji 9 Jamaica DONE! Jamaica Notice how the output from each thread is intermingled with the output from the other. This is because both SimpleThread threads are running concurrently. Thus, both run methods are running at the same time and each thread is displaying its output at the same time as the other. Implementing the Runnable Interface The Clock class shown below displays the current time every second. The main method starts the clock printing thread going and then reads the terminal. When it gets input it sets a flag so that the printing thread will terminate. This Clock class implements the Runnable interface (and implements the run method defined in it). Clock then creates a thread and provides an instance of itself as an argument to the Thread's constructor. When created in this way, the Thread gets its run method from the object passed into the constructor. The Clock class import java.util.*; import java.text.dateformat; public class Clock implements Runnable { boolean run = true; public static void main(string args[]) throws java.io.ioexception { Clock clock = new Clock(); Thread clockthread = new Thread(clock, "Clock"); clockthread.start(); System.in.read(); clock.run = false; while (run) { Calendar cal = Calendar.getInstance(); Date date = cal.gettime(); // format it and display it DateFormat dateformatter = DateFormat.getTimeInstance(); System.out.println(dateFormatter.format(date)); Thread.sleep(1000); catch (InterruptedException e){ // somebody interrupted us, // so get back to work > java Clock 9:31:54 PM 9:31:55 PM Deciding to Use the Runnable Interface There are two ways to provide the run method for a Java thread: Subclass the Thread class defined in the java.lang package and override the run method. Provide a class that implements the Runnable interface (defined in the java.lang package) and therefore implements the run method. In this case, a Runnable object provides the run method to the thread. Example: See the Clock class just shown. If your class must subclass some other class (the most common example being Applet), you should use the Runnable interface Interface Runnable Classes that implement Runnable can also be run as separate threads Runnable classes have a run() method In this case you create a thread specifying the Runnable object as the constructor argument Example public class DownCounter implements Runnable { for (int i=10; i>0; i--) System.out.println( Down: + i); public static void main(string args[]) { DownCounter ct = new DownCounter(); Thread t = new Thread(ct); t.start(); > java DownCounter Down: 10 Down: 9 Down: 8 Down: 7 Down: 6 Down: 5 Down: 4 Down: 3 Down: 2 Down: 1

Many public class Many extends Thread { private int retry; private String info; public Many (int retry, String info) { this.retry = retry; this.info = info; public void run () { for ( int n = 0; n < retry; ++ n) work(); quit(); protected void work () { System.out.print(info); protected void quit () { System.out.print('\n'); public static void main (String args []) { if (args!= null) for (int n = 0; n < args.length; ++n) new Many( args.length, args[n]).start(); > java Many a Hi There aaa HiHiHi ThereThereThere When Execution Ends The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been called All threads that are not daemon threads have died, either by returning from the call to the run() or by throwing an exception that propagates beyond run(). You cannot restart a dead thread, but you can access its state and behavior. Thread Scheduling Threads are scheduled like processes Thread states Running Waiting, Sleeping, Suspended, Blocked Ready Dead When you invoke start() the Thread is marked ready and placed in the thread queue Thread States The following diagram shows the states that a Java thread can be in during its life. It also illustrates which method calls cause a transition to another state. This figure is not a complete finite state diagram, but rather an overview of the more interesting and common facets of a thread's life. completed New start run Ready yield Running Finished sleep wait The Life Cycle of a Thread Creation Starting Alternating between Runnable Inactive Finishing or Dead Creating a Thread notify notifyall Inactive Notice that this--the Clock instance-- is the first argument to the thread constructor. The first argument to this thread constructor must implement the Runnable interface and provides the thread with its run method. The second argument is just a name for the thread. Starting a Thread The start method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread's run method. The thread's run method is the one defined in the Clock class. After the start method has returned, the thread is in the Runnable state. With a single processor the Java runtime system must implement a scheduling scheme that shares the processor between all "running" threads. At any given time, a "running" thread actually may be waiting for its turn in the CPU. The Clock's run method loops while the boolean variable run is true. Within the loop, the thread prints the time and then tells the thread to sleep for one second (1000 milliseconds).

Making a Thread Not Runnable A thread becomes Not Runnable when one of these events occurs: Its sleep method is invoked. The thread calls the wait method to wait for a specific condition to be satisifed. The thread is blocking on I/O. The clockthread in the Clock applet becomes Not Runnable when the run method calls sleep on the current thread. During the second that the clockthread is asleep, the thread does not run, even if the processor becomes available. After the second has elapsed, the thread becomes Runnable again and, if the processor becomes available, the thread begins running again. For each entrance into the Not Runnable state, there is a specific and distinct condition that returns the thread to the Runnable state. A condition works only for its corresponding entrance. This describes the exit condition for every entrance into the Not Runnable state: If a thread has been put to sleep, then the specified number of milliseconds must elapse. If a thread is waiting for a condition, then another object must notify the waiting thread of a change in condition by calling notify or notifyall. If a thread is blocked on I/O, then the I/O must complete. Stopping a Thread A thread generally arranges for its own death by having a run method that terminates naturally. For example, the while loop in this run method is a finite loop-- it will iterate 100 times and then exit: int i = 0; while (i < 100) { i++; System.out.println("i = " + i); A thread with this run method dies naturally when the loop completes and the run method exits. The Clock applet thread arranges for its own death when the variable run is set false. The exit condition for this run method is the exit condition for the while loop because there is no code after the while loop. The isalive Method The API for the Thread class includes a method called isalive(). The isalive() method returns true if the thread has been started and not stopped. If the isalive() method returns false, you know that the thread either is a New Thread or is Dead. If the isalive() method returns true, you know that the thread is either Runnable or Not Runnable. You cannot differentiate between a New Thread or a Dead thread. Nor can you differentiate between a Runnable thread and a Not Runnable thread. public class WorkerThread extends Thread { private int result = 0; // Perform a complicated time consuming calculation // and store the answer in the variable result public static void main(string args []) { WorkerThread t = new WorkerThread (); t.start(); while ( t.isalive() ) { // What is wrong with this? sleep() System.out.println ( result ); Puts the currently executing thread to sleep for the specified number of milliseconds sleep(int milliseconds) sleep(int millisecs, int nanosecs) Sleep can throw an InterruptedException The method is static and can be accessed as Thread.sleep() public class WorkerThread extends Thread { private int result = 0; // Perform a complicated time consuming calculation // and store the answer in the variable result public static void main(string args []) { WorkerThread t = new WorkerThread (); t.start(); while ( t.isalive() ) sleep( 100 ); catch ( InterruptedException ex ) { System.out.println ( t.result ); yield() A call to the static method yield()causes the currently executing thread to go to the ready state (this is done by the thread itself) public class WorkerThread extends Thread { private int result = 0; // Perform a complicated time consuming calculation // and store the answer in the variable result public static void main(string args []) { WorkerThread t = new WorkerThread (); t.start(); while ( t. isalive() ) yield() System.out.println ( result );

Joining Threads Calling isalive() to determine when a thread has terminated is probably not the best way to accomplish this What would be better is to have a method that once invoked would wait until a specified thread has terminated join() does exactly that join() join(long timeout) join(long timeout, int nanos) Like sleep(), join() is static and can throw an InterruptedException public class WorkerThread extends Thread { private int result = 0; // Perform a complicated time consuming calculation // and store the answer in the variable result public static void main(string args []) { WorkerThread t = new WorkerThread (); t.start(); t.join(); catch ( InterruptedException ex ) { System.out.println ( result ); Thread Priorities Threads can have priorities from 1 to 10 (10 is the highest priority) The default priority is 5 The constants Thread.MAX_PRIORITY, Thread.MIN_PRIORITY, and Thread.NORM_PRORITY give the actual values Priorities can be changed via setpriority() Priorities can be checked via getpriority() When multiple threads are ready to be executed, the runtime system runs the runnable thread with the highest priority for execution. Only when that thread stops, yields, or becomes not runnable will a lower priority thread start executing. Two threads of the same priority are chosen in a round-robin fashion. The chosen thread will run until one of the following conditions is true: A higher priority thread becomes runnable. It yields, or its run method exits. On systems that support time-slicing, its time allotment has expired. Then the second thread is given a chance to run, and so on, until the JVM exits. Java's thread scheduling algorithm is preemptive. If at any time a thread with a higher priority than all other runnable threads becomes runnable, the runtime system chooses the new higher priority thread for execution. Generally, the highest priority thread is running. However, this is not guaranteed. The scheduler may choose to run a lower priority thread to avoid starvation. For this reason, use priority only to affect scheduling policy for efficiency purposes. Do not rely on thread priority for algorithm correctness. Understanding Thread Priority Time-Slicing Most systems fight selfish thread behavior with a strategy known as time-slicing. When there are multiple "Runnable" threads of equal priority and those threads are the highest priority threads competing for the CPU the scheduler switches between them. The Java runtime does not implement (and therefore does not guarantee) time-slicing. However, some systems on which you can run Java do support time-slicing. Your Java programs should not rely on time-slicing as it may produce different results on different systems. In general, you should try to write "well-behaved" threads that voluntarily relinquish the CPU periodically and give other threads an opportunity to run. In particular, you should never write Java code that relies on time-sharing-- this will practically guarantee that your program will give different results on different computer systems. A thread can voluntarily yield the CPU without going to sleep or some other drastic means by calling the yield method. The yield method gives other threads of the same priority a chance to run. If there are no equal priority threads that are runnable, then the yield is ignored. Using the Timer and TimerTask Classes The Timer class in that package schedules instances of a class called TimerTask. import java.util.timer; import java.util.timertask; // schedule a task once 5 seconds have passed. public class Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); class RemindTask extends TimerTask { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread public static void main(string args[]) { System.out.println("About to schedule task."); new Reminder(5); System.out.println("Task scheduled."); >java Reminder About to schedule task. Task scheduled. --------------five second wait--------------- Time's up!

Using the Timer and TimerTask classes Implement a custom subclass of TimerTask. The run method contains the code that performs the task. Create a thread by instantiating the Timer class. Instantiate the timer task object with: new RemindTask(). Schedule the instance of TimerTask for execution using one of the schedule methods in Timer. Schedule for execution at the specified time. void schedule(timertask task, Date time) Schedule for repeated fixed-delay execution, beginning at the specified time. void schedule(timertask task, Date firsttime, long period) Schedule for execution after the specified delay. void schedule(timertask task, long delay) Schedule for repeated fixed-delay execution, beginning after the specified delay. void schedule(timertask task, long delay, long period) Schedule for repeated fixed-rate execution, beginning at the specified time. void scheduleatfixedrate(timertask task, Date firsttime, long period) Schedule for repeated fixed-rate execution, beginning after the specified delay. void scheduleatfixedrate(timertask task, long delay, long period) Stopping Timer Threads By default, a program keeps running as long as any threads, including timer threads, are running. You can terminate a timer thread in four ways. Invoke cancel on the timer. You can do this from anywhere in the program. Make the timer s thread a daemon by creating the timer with: new Timer(true). After all the timer s scheduled tasks have finished executing, remove all references to the Timer object. Invoke the System.exit method. Synchronization - A Bank Account Suppose we have a BankAccount object that stores a bank balance. Then we can have a thread that deposits money into the account and a thread that withdraws money. Several Customers share data through a common BankAccount object. None of the Customers make any effort to synchronize their activities. What problems might arise? One problem arises when one Customer is quicker than another Customer and deposits money while the other Customer is still calculating the balance which will overwrite the new deposit. This is wrong. The Customer The Customer deposits (or withdraws) a fixed amount into a BankAccount object. The Customer sleeps for a random amount of time between 0 and 100 milliseconds while it is calculating the new balance: public class Customer extends Thread { private BankAccount bankaccount; private int amount; public Customer(BankAccount b, int amount) { bankaccount = b; this.amount = amount; for (int i = 0; i < 10; i++) { sleep((int)(math.random() * 100)); catch (InterruptedException e) { int temp = bankaccount.get(); System.out.println("Customer #" + this.amount + " old balance: " + temp); sleep((int)(math.random() * 100)); catch (InterruptedException e) { temp = temp + amount; bankaccount.put(temp); System.out.println("Customer #" + this.amount + " new balance: " + temp); The BankAccount and test program public class BankAccount { private int balance; public int get() { return balance; public void put(int amount) { balance = amount; public class BankTest { public static void main(string[] args) { BankAccount b = new BankAccount(); Customer c1 = new Customer(b, 1); Customer c2 = new Customer(b, 2); c1.start(); c2.start();

Output >java BankTest Customer #1 old balance: 0 Customer #1 new balance: 1 Customer #1 old balance: 1 Customer #2 old balance: 1 Customer #1 new balance: 2 Customer #1 old balance: 2 Customer #2 new balance: 3 Customer #2 old balance: 3 Customer #2 new balance: 5 Customer #2 old balance: 5 Customer #1 new balance: 3 Customer #1 old balance: 3 Customer #2 new balance: 7 Customer #1 new balance: 4 Customer #2 old balance: 4 Customer #2 new balance: 6 Customer #1 old balance: 6 Customer #2 old balance: 6 Customer #1 new balance: 7 Customer #1 old balance: 7 Customer #2 new balance: 8 Customer #1 new balance: 8 Customer #2 old balance: 8 Customer #1 old balance: 8 Customer #2 new balance: 10 Customer #1 new balance: 9 Customer #2 old balance: 9 Customer #2 new balance: 11 Customer #1 old balance: 11 Customer #2 old balance: 11 Customer #2 new balance: 13 Customer #1 new balance: 12 Customer #2 old balance: 12 Customer #1 old balance: 12 Customer #2 new balance: 14 Customer #1 new balance: 13 Customer #2 old balance: 13 Customer #1 old balance: 13 Customer #2 new balance: 15 Customer #1 new balance: 14 Synchronizing Threads How do we safely share data between simultaneously running threads? Suppose one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. Or, as you type characters on the keyboard, the producer thread places key events in an event queue and the consumer thread reads the events from the same queue. There must be some mechanism to prevent a thread from using inconsistent data because another thread is in the process of modifying the data. Synchronization Every object has a lock that can be held by at most one thread at a time A thread gets a lock by entering a synchronized block of code A thread can give up a lock by: leaving a block of synchronized code calling lock.wait() A thread executing wait() can be released by: lock.notify() some waiting thread is allowed to compete for the lock lock.notifyall() all waiting threads are allowed to compete for the lock Synchronized Code There are two ways to mark code as synchronized: use the synchronize statement synchronize( someobject) { // must obtain lock to enter this block. // wait() ing threads have to reacquire the // lock before they are allowed to proceed. using the synchronized method shorthand public synchronized somemethod() { which the same as public somemethod () { synchronized( this ) { Locking an Object The code segments within a program that access the same object from separate, concurrent threads are called critical sections. In the Java language, a critical section can be a block or a method and are identified with the synchronized keyword. The Java platform then associates a lock with every object that has synchronized code. In the bank account example, the code in the Customer run method from where it gets the old balance until it stores the new balance is a critical section. Another Customer thread should not access the same BankAccount while the Customer run method is changing it. So we should put this critical code in a synchronized block and lock the BankAccount object. A synchronized Customer: public class Customer1 extends Thread { private BankAccount1 bankaccount; private int amount; public Customer1(BankAccount1 b, int amount) { bankaccount = b; this.amount = amount; for (int i = 0; i < 10; i++) { sleep((int)(math.random() * 100)); catch (InterruptedException e) { synchronized (bankaccount) { int temp = bankaccount.get(); System.out.println("Customer #" + this.amount + " old balance: " + temp); sleep((int)(math.random() * 100)); catch (InterruptedException e) { temp = temp + amount; bankaccount.put(temp); System.out.println("Customer #" + this.amount + " new balance: " + temp);

Synchronized Output >java BankTest1 Customer #1 old balance: 0 Customer #1 new balance: 1 Customer #2 old balance: 1 Customer #2 new balance: 3 Customer #1 old balance: 3 Customer #1 new balance: 4 Customer #2 old balance: 4 Customer #2 new balance: 6 Customer #2 old balance: 6 Customer #2 new balance: 8 Customer #1 old balance: 8 Customer #1 new balance: 9 Customer #2 old balance: 9 Customer #2 new balance: 11 Customer #1 old balance: 11 Customer #1 new balance: 12 Customer #2 old balance: 12 Customer #2 new balance: 14 Customer #1 old balance: 14 Customer #1 new balance: 15 Customer #2 old balance: 15 Customer #2 new balance: 17 Customer #1 old balance: 17 Customer #1 new balance: 18 Customer #2 old balance: 18 Customer #2 new balance: 20 Customer #1 old balance: 20 Customer #1 new balance: 21 Customer #2 old balance: 21 Customer #2 new balance: 23 Customer #1 old balance: 23 Customer #1 new balance: 24 Customer #1 old balance: 24 Customer #1 new balance: 25 Customer #1 old balance: 25 Customer #1 new balance: 26 Customer #2 old balance: 26 Customer #2 new balance: 28 Customer #2 old balance: 28 Customer #2 new balance: 30 A synchronized bank Rather than require the customers of a bank to synchronize themselves with the correct bank it is better for the bank to provide a safe, synchronized interface It is always better to provide a safe interface than to require your clients to use your interface in a safe way. The customers do not have to worry about synchronization The bank performes all of its critical work in a single synchronized method Whenever control enters a synchronized method, the thread that called the method locks the object whose method has been called. Other threads cannot call a synchronized method on the same object until the object is unlocked. By declaring the method adjustbalance to be synchronized the lock on the BankAccount object is acquired when the method starts and is released when the method is exited. Synchronized bank code public class Customer2 extends Thread { private BankAccount2 bankaccount; private int amount; public Customer2(BankAccount2 b, int amount) { bankaccount = b; this.amount = amount; for (int i = 0; i < 10; i++) { sleep((int)(math.random() * 100)); catch (InterruptedException e) { bankaccount.adjustbalance(amount); public class BankAccount2 { private int balance; public synchronized void adjustbalance(int amount) { int temp = balance; System.out.println("Customer #" + amount + " old balance: " + temp); Thread.sleep((int)(Math.random() * 100)); catch (InterruptedException e) { temp = temp + amount; balance = temp; System.out.println("Customer #" + amount + " new balance: " + temp); Synchronized Static Methods Java also provides synchronized static methods. Before a synchronized static method is executed, the calling thread must first obtain the class lock. Since there is only one class lock, at most one thread can hold the lock for the class (object locks can be held by different threads locking on different instances of the class). Reaquiring a Lock The Java runtime system allows a thread to re-acquire a lock that it already holds (i.e., acquire the same lock multiple times) because Java locks are reentrant. Reentrant locks are important because they eliminate the possibility of a single thread deadlocking itself on a lock that it already holds. Consider this class: public class Reentrant { public synchronized void a() { b(); System.out.println("here I am, in a()"); public synchronized void b() { System.out.println("here I am, in b()"); Reentrant contains two synchronized methods: a and b. The first synchronized method, a, calls the other synchronized method, b. When control enters method a, the current thread acquires the lock for the Reentrant object. Now, a calls b and because b is also synchronized the thread attempts to acquire the same lock again. Because Java supports reentrant locks, this works. The current thread can acquire the Reentrant object's lock again and both a and b execute to conclusion as is evidenced by the output: here I am, in b() here I am, in a() In systems that don't support reentrant locks, this sequence of method calls would cause deadlock.

wait()/notify() In all of the previous examples a thread gave up a lock when it left the synchronized block It is possible for a thread to give up a lock while it is in a synchronized block The method wait()is executed on the object whose lock the thread is holding The thread will resume execution via a call to the lock object s notify() method Has The Lock Not Runnable Runnable wait() notify() notifyall JVM Selects Next Thread Using the notifyall and wait Methods If we don t like negative balances in the accounts we have to delay any transaction when there is not enough money. The wait method releases the lock on the object and allows other methods to acquire this lock. The current thread doesn t run until another thread calls the notifyall (or notify) method. Then this thread competes for the lock and, if successful, gets the lock and continues execution. The notifyall method wakes up all threads waiting on the object in question. The awakened threads compete for the lock. One thread gets it, and the others go back to waiting. The Object class also defines the notify method, which arbitrarily wakes up one of the threads waiting on this object. It is generally better to use notifyall if you are not sure that any thread will do. The Object class contains not only the version of wait without arguments which waits indefinitely for notification, but also two other versions of the wait method: wait(long timeout) Waits for notification or until the timeout period has elapsed. timeout is measured in milliseconds. wait(long timeout, int nanos) Waits for notification or until timeout milliseconds plus nanos nanoseconds have elapsed. Bank with negative balance protection public class BankAccount3 { private int balance; public synchronized void adjustbalance(int amount) { while( balance + amount < 0 ) { wait(); catch ( InterruptedException e) { int temp = balance; System.out.println("Customer #" + amount + " old balance: " + temp); Thread.sleep((int)(Math.random() * 100)); catch (InterruptedException e) { temp = temp + amount; balance = temp; System.out.println("Customer #" + amount + " new balance: " + temp); if( balance > 0 ) { notifyall(); public class BankTest3 { public static void main(string[] args) { BankAccount3 b = new BankAccount3(); Customer3 c1 = new Customer3(b, 1); Customer3 c2 = new Customer3(b, -3); Customer3 c3 = new Customer3(b, 2); c1.start(); c2.start(); Thread.sleep(1000); catch ( InterruptedException e) { c3.start(); Output >java BankTest3 Customer #1 old balance: 0 Customer #1 new balance: 1 Customer #1 old balance: 1 Customer #1 new balance: 2 Customer #1 old balance: 2 Customer #1 new balance: 3 Customer #-3 old balance: 3 Customer #-3 new balance: 0 Customer #1 old balance: 0 Customer #1 new balance: 1 Customer #1 old balance: 1 Customer #1 new balance: 2 Customer #1 old balance: 2 Customer #1 new balance: 3 Customer #-3 old balance: 3 Customer #-3 new balance: 0 Customer #1 old balance: 0 Customer #1 new balance: 1 Customer #1 old balance: 1 Customer #1 new balance: 2 Customer #1 old balance: 2 Customer #1 new balance: 3 Customer #-3 old balance: 3 Customer #-3 new balance: 0 Customer #1 old balance: 0 Customer #1 new balance: 1 Customer #2 old balance: 1 Customer #2 new balance: 3 Customer #-3 old balance: 3 Customer #-3 new balance: 0 Customer #2 old balance: 0 Customer #2 new balance: 2 Customer #2 old balance: 2 Customer #2 new balance: 4

Customer #-3 old balance: 4 Customer #-3 new balance: 1 Customer #2 old balance: 1 Customer #2 new balance: 3 Customer #2 old balance: 3 Customer #2 new balance: 5 Customer #-3 old balance: 5 Customer #-3 new balance: 2 Customer #2 old balance: 2 Customer #2 new balance: 4 Customer #-3 old balance: 4 Customer #-3 new balance: 1 Customer #2 old balance: 1 Customer #2 new balance: 3 Customer #2 old balance: 3 Customer #2 new balance: 5 Customer #-3 old balance: 5 Customer #-3 new balance: 2 Customer #2 old balance: 2 Customer #2 new balance: 4 Customer #2 old balance: 4 Customer #2 new balance: 6 Customer #-3 old balance: 6 Customer #-3 new balance: 3 Customer #-3 old balance: 3 Customer #-3 new balance: 0 Test 1 public class Locks1 extends Thread { private Object lock; private int myid; public Locks1( Object l, int id ) { lock = l; myid = id; public void method() { synchronized( lock ) { for ( int i = 0; i < 3; i++ ) { System.out.println( "Thread #" + myid + " is tired" ); Thread.currentThread ().sleep( 10 ); catch ( InterruptedException e ){ System.out.println ("Thread #" + myid + " is rested" ); method(); public static void main( String args[] ) { Integer lock = new Integer( 0 ); for ( int i = 0; i < 3; i++ ) new Locks1( lock, i ).start(); Answer 1 Since all the threads are using the same object for the lock, each thread will run its method() to completion before another thread can get the lock. Test 2 public class Locks2 extends Thread { private Object lock = new Integer( 0 ); private int myid; public Locks2( int id ) { myid = id; public void method() { synchronized ( lock ) { for ( int i = 0; i < 3; i++ ) { System.out.println ( "Thread #" + myid + " is tired" ); Thread.currentThread ().sleep( 10 ); catch ( InterruptedException e ){ System.out.println ( "Thread #" + myid + " is rested" ); method(); public static void main( String args[] ) { for ( int i = 0; i < 3; i++ ) new Locks2( i ).start(); Answer 2 There is no synchronization here because each thread has a different lock. the thread still has to get the lock to enter the synchronized block, but since the lock s are all different the synchronization is lost.

Test 3 public class Locks3 extends Thread { private static Object lock = new Integer( 0 ); private int myid ; public Locks3( int id ) { myid = id; public void method() { synchronized ( lock ) { for ( int i = 0; i < 3; i++ ) { System.out.println ( "Thread #" + myid + " is tired" ); Thread.currentThread ().sleep( 10 ); catch ( InterruptedException e ){ System.out.println ( "Thread #" + myid + " is rested" ); method(); public static void main( String args[] ) { for ( int i = 0; i < 3; i++ ) new Locks3( i ).start(); Answer 3 Here we have synchronization because the lock is a static member. This means that regardless of the number of objects that are instantiated from this class, there will always be exactly one lock. Test 4 public class Locks4 extends Thread { private int myid ; public Locks4( int id ) { myid = id; public synchronized void method() { for ( int i = 0; i < 3; i++ ) { System.out.println( "Thread #" + myid + " is tired" ); Thread.currentThread().sleep( 10 ); catch ( InterruptedException e ){ System.out.println( "Thread #" + myid + " is rested" ); method(); Answer 4 No synchronization because each thread is locking on a different Locks4 object. SyncQueue public class SyncQueue { private Object q[]; private int head; private int tail; private int count; private int cap; public SyncQueue( int size) { q = new Object[size]; head = 1; tail = 0; count = 0; cap = size; public synchronized void enqueue (Object o) { if (!isfull() ) { tail = ( tail + 1 ) % cap; q[ tail ] = o; count++; public synchronized Object dequeue() { Object retval = null; if (!isempty() ) { retval = q[ head ]; head = ( head + 1 ) % cap; count--; return retval; public Object peek() { // is this safe? Object retval = null; if (!isempty() ) retval = q[head]; return retval; public boolean isempty() { return count == 0; public boolean isfull () { return count == cap; public static void main( String args[] ) { for ( int i = 0; i < 3; i++ ) new Locks( i ).start();

suspend() The thread class has a suspend() method A suspended thread remains suspended until it is resumed by another thread This method has been deprecated, as it is deadlockprone: A suspended thread holds any locks that it may have. If the thread holds a lock, no thread can obtain the lock until the target thread is resumed. If the thread that would resume the target thread attempts to obtain the lock prior to calling resume, deadlock results. resume()is deprecated as well (it is more or less useless without suspend() stop() and stop(e) The thread class has a stop() method Forces a thread to stop executing Can be invoked by another thread This method has been deprecated, as it is unsafe: Stopping a thread with Thread.stop causes it to release all of the locks that it has holding If any of the objects protected by these locks are in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. Example private boolean continue = true; public void stop() { continue = false while (continue) { thisthread.sleep(100); catch ( InterruptedException e){ The dining philosophers Five philosophers sit at a round table. In front of each philosopher is a bowl of rice. Between each pair of philosophers is one chopstick. Before any individual philosopher can take a bite of rice she must have two chopsticks--one taken from the left, and one taken from the right. The philosophers must find some way to share chopsticks such that they all get to eat. Assume each philosopher always reaches for the chopstick on her right first. If the chopstick is there, she takes it and raises her right hand. Next, she tries for the left chopstick. If the chopstick is available, she picks it up and raises her other hand. Now that she has both chopsticks, she takes a bite of rice and says "Mmm!" She then puts both chopsticks down, allowing either of her two neighbors to get the chopsticks. She then starts all over again by trying for the right chopstick. Between each attempt to grab a chopstick, each philosopher pauses for a random period of time. If none of the philosophers wait before starting--they just grab--then probably the philosophers end up frozen with their right hand in the air. Why? Because each philosopher immediately grabs one chopstick and is waiting on a condition that cannot be satisfied--they are all waiting for the left chopstick, which is held by the philosopher to their left. If the philosophers wait a random amount of time before starting then deadlock is not as likely at the beginning. However, deadlock is always possible with this particular implementation of the dining philosophers problem because it is possible for all five philosophers to be holding their right chopsticks. Rather than rely on luck to prevent deadlock, you must either prevent it or detect it. Avoiding Starvation and Deadlock The best choice is to prevent deadlocks rather than to try and detect them. The simplest approach to preventing deadlock is to impose ordering on the condition variables. For the dining philosophers, there is no ordering imposed on the condition variables because they and the chopsticks are arranged in a circle. All chopsticks are equal. However, we can change the rules in the applet by numbering the chopsticks 1 through 5 and insisting that the philosophers pick up the chopstick with the lower number first. The philosopher who is sitting between chopsticks 1 and 2 and the philosopher who is sitting between chopsticks 1 and 5 must now reach for the same chopstick first (chopstick 1) rather than picking up the one on the right. Whoever gets chopstick 1 first is now free to take another one. Whoever doesn't get chopstick 1 must now wait for the first philosopher to release it. Deadlock is not possible. Code public class Philosophers { static void main(string args[] ) { Object[] fork = new Object[5]; Phil[] phil = new Phil[5]; for( int i = 0; i < 5; i++ ) { fork[i] = new Object(); for( int i = 0; i < 5; i++ ) { phil[i] = new Phil(i, fork[i], fork[(i+1)%5], 40, 10, 10); for( int i = 0; i < 5; i++ ) { phil[i].start();

The Phil class static class Phil extends Thread { int num, wait, left, right; Object leftfork, rightfork; public Phil(int i, Object l, Object r, int d1, int d2, int d3 ) { num = i; leftfork = l; rightfork = r; wait = d1; left = d2; right = d3; while( true ) { delay( wait ); synchronized( leftfork ) { System.out.println("#"+num+" has one fork"); delay( left ); synchronized( rightfork ) { System.out.println("#"+num+" eating"); delay( right ); System.out.println("#"+num+" done"); rightfork.notifyall(); leftfork.notifyall(); void delay( int time ) { Thread.sleep((int)(Math.random() * time)); catch (InterruptedException e) { Sample run >java Philosophers #0 has one fork #4 has one fork #1 has one fork #1 eating #1 done #2 has one fork #0 eating #2 eating #0 done #4 eating #4 done #2 done #3 has one fork #3 eating... #2 eating #4 has one fork #2 done #1 eating #1 done #0 eating #0 done #4 eating #4 done #2 has one fork #3 has one fork #3 eating #3 done #2 eating #2 done #4 has one fork #2 has one fork #0 has one fork #1 has one fork #3 has one fork Thread Groups Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once. For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the ThreadGroup class in the java.lang package. The runtime system puts a thread into a thread group during thread construction. When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group. The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created. The Default Thread Group If you create a new Thread without specifying its group in the constructor, the new thread is placed in the same group as the thread that created it. When a Java application first starts up, the Java runtime system creates a ThreadGroup named main. Unless specified otherwise, all new threads that you create become members of the main thread group. Creating a Thread Explicitly in a Group The Thread class has three constructors that let you set a new thread's group: public Thread(ThreadGroup group, Runnable runnable) public Thread(ThreadGroup group, String name) public Thread(ThreadGroup group, Runnable runnable, String name) Getting a Thread's Group To find out what group a thread is in, you can call its getthreadgroup method: thegroup = mythread.getthreadgroup(); The ThreadGroup class has methods that can be categorized as follows: Collection Management Methods--Methods that manage the collection of threads and subgroups contained in the thread group. Methods That Operate on the Group--These methods set or get attributes of the ThreadGroup object. Methods That Operate on All Threads within a Group--This is a set of methods that perform some operation, such as start or resume, on all the threads and subgroups within the ThreadGroup. Access Restriction Methods--ThreadGroup and Thread allow the security manager to restrict access to threads based on group membership.