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

Size: px
Start display at page:

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

Transcription

1 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".

2 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

3 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).

4 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 );

5 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!

6 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();

7 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);

8 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.

9 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

10 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.

11 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();

12 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();

13 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.

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

Definition: A thread is a single sequential flow of control within a program. What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.

More information

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

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

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

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004 Thread Programming Comp-303 : Programming Techniques Lecture 11 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 11 Comp 303 : Programming Techniques Page 1 Announcements

More information

CIS233J Java Programming II. Threads

CIS233J Java Programming II. Threads CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential

More information

CS 556 Distributed Systems

CS 556 Distributed Systems CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that

More information

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

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

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

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

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

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

More information

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

More information

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

Object Oriented Programming (II-Year CSE II-Sem-R09) (II-Year CSE II-Sem-R09) Unit-VI Prepared By: A.SHARATH KUMAR M.Tech Asst. Professor JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, HYDERABAD. (Kukatpally, Hyderabad) Multithreading A thread is a single sequential

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

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

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

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

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

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

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

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

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

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

Java Threads. Thread. Rui Moreira. control within a program. threads. performed concurrently Java Threads Rui Moreira Links: http://java.sun.com/docs/books/tutorial/essential/threads/index.html Thread Thread comprises 3 parts: n Leightwheight process n Single and sequential flow of control within

More information

Multithread Computing

Multithread Computing Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

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

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

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

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1) Advanced Programming Methods Lecture 6 - Concurrency in Java (1) Overview Introduction Java threads Java.util.concurrent References NOTE: The slides are based on the following free tutorials. You may want

More information

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

Java Threads. Written by John Bell for CS 342, Spring 2018 Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.

More information

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

Multithreaded Programming

Multithreaded Programming core programming Multithreaded Programming 1 2001-2003 Marty Hall, Larry Brown http:// 2 Multithreaded Programming Agenda Why threads? Approaches for starting threads Separate class approach Callback approach

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

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

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

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

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Chapter 19 Multithreading

Chapter 19 Multithreading Chapter 19 Multithreading Prerequisites for Part VI Chapter 14 Applets, Images, and Audio Chapter 19 Multithreading Chapter 20 Internationalization 1 Objectives To understand the concept of multithreading

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

Unit - IV Multi-Threading

Unit - IV Multi-Threading Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first

More information

COE518 Lecture Notes Week 7 (Oct 17, 2011)

COE518 Lecture Notes Week 7 (Oct 17, 2011) coe518 (Operating Systems) Lecture Notes: Week 7 Page 1 of 10 COE518 Lecture Notes Week 7 (Oct 17, 2011) Topics multithreading in Java Note: Much of this material is based on http://download.oracle.com/javase/tutorial/essential/concurrency/

More information

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

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University Threads & Timers CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Multi-tasking When you re working, how many different applications do you have open at one

More information

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

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

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

More information

Advanced Concepts of Programming

Advanced Concepts of Programming Berne University of Applied Sciences E. Benoist / E. Dubuis January 2005 1 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

Techniques of Java Programming: Concurrent Programming in Java

Techniques of Java Programming: Concurrent Programming in Java Techniques of Java Programming: Concurrent Programming in Java Manuel Oriol May 11, 2006 1 Introduction Threads are one of the fundamental structures in Java. They are used in a lot of applications as

More information

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

Reading from URL. Intent - open URL  get an input stream on the connection, and read from the input stream. Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)

More information

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

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 Contents G53SRP: Java Threads Chris Greenhalgh School of Computer Science 1 Definition Motivations Threads Java threads Example embedded process Java Thread API & issues Exercises Book: Wellings 1.1 &

More information

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

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 Session objectives Introduction Creating thread Thread class

More information

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

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

More information

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.

More information

THREADS AND CONCURRENCY

THREADS AND CONCURRENCY THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

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

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

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

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

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

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING UNIT IV MULTITHREADING AND GENERIC PROGRAMMING Differences between multithreading and multitasking, thread life cycle, creating threads, creating threads, synchronizing threads, Inter-thread communication,

More information

Reintroduction to Concurrency

Reintroduction to Concurrency Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking

More information

Threads in Java (Deitel & Deitel)

Threads in Java (Deitel & Deitel) Threads in Java (Deitel & Deitel) OOutline 1 Introduction 1 Class Thread: An Overview of the Thread Methods 1 Thread States: Life Cycle of a Thread 1 Thread Priorities and Thread Scheduling 1 Thread Synchronization

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 4/26/16 Announcements BRING YOUR CORNELL ID TO THE PRELIM. 2 You need it to get in THREADS & CONCURRENCY Prelim 2 is next Tonight BRING YOUR CORNELL ID! A7 is due Thursday. Our Heap.java: on Piazza (A7

More information

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

Threads, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

More information

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

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

More information

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

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions? Project Threads Synchronization Minimum submission Deadline extended to tonight at midnight Early submitters 10 point bonus TSP Still due on Tuesday! Before we begin Plan for today Thread synchronization

More information

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

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer. CMSC 330: Organization of Programming Languages Threads Computation Abstractions t1 t2 t1 t3 t2 t1 p1 p2 p3 p4 CPU 1 CPU 2 A computer t4 t5 Processes (e.g., JVM s) Threads CMSC 330 2 Processes vs. Threads

More information

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

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

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

Unit 4. Thread class & Runnable Interface. Inter Thread Communication Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more

More information

Synchronization

Synchronization Synchronization 10-28-2013 Synchronization Coming next: Multithreading in JavaFX (javafx.concurrent) Read: Java Tutorial on concurrency JavaFX Tutorial on concurrency Effective Java, Chapter 9 Project#1:

More information

Interprocess Communication By: Kaushik Vaghani

Interprocess Communication By: Kaushik Vaghani Interprocess Communication By: Kaushik Vaghani Background Race Condition: A situation where several processes access and manipulate the same data concurrently and the outcome of execution depends on the

More information

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing

More information

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

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some

More information

Programming Language Concepts: Lecture 11

Programming Language Concepts: Lecture 11 Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Java implementations of concurrency process and threads

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late

More information

Concurrent Computing CSCI 201 Principles of Software Development

Concurrent Computing CSCI 201 Principles of Software Development Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking

More information

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

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Synchronized Methods of Old Versions of Java

Synchronized Methods of Old Versions of Java Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs next week for a demo time In case you hadn t noticed Classes end Thursday April 15

More information

Basics of. Multithreading in Java

Basics of. Multithreading in Java Basics of programming 3 Multithreading in Java Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

Java Programming Lecture 23

Java Programming Lecture 23 Java Programming Lecture 23 Alice E. Fischer April 19, 2012 Alice E. Fischer () Java Programming - L23... 1/20 April 19, 2012 1 / 20 Outline 1 Thread Concepts Definition and Purpose 2 Java Threads Creation

More information

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

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2016 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

More information

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

By: Abhishek Khare (SVIM - INDORE M.P) By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying

More information

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

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2) Network Programming COSC 1176/1179 Lecture 6 Concurrent Programming (2) Threads Recall from last week Every line of Java code is part of a thread There can be one or more threads running in parallel Each

More information

Component-Based Software Engineering

Component-Based Software Engineering Component-Based Software Engineering More stuff on Threads Paul Krause Lecture 7 - Contents Basics of threads and synchronization Waiting - releasing locks Collection Plate example Choices when pausing

More information

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

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking) What is a Thread? 2 THREADS AND CONCURRENCY A separate process that can perform a computational task independently and concurrently with other threads Most programs have only one thread GUIs have a separate

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread

More information

CS360 Lecture 12 Multithreading

CS360 Lecture 12 Multithreading CS360 Lecture 12 Multithreading Thursday, March 11, 2004 Reading Multithreading: Chapter 16 Thread States At any time, a thread can be in one of several thread states: - Born: this is the time when the

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Synchronization in Concurrent Programming. Amit Gupta

Synchronization in Concurrent Programming. Amit Gupta Synchronization in Concurrent Programming Amit Gupta Announcements Project 1 grades are out on blackboard. Detailed Grade sheets to be distributed after class. Project 2 grades should be out by next Thursday.

More information

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

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008. CSC 4103 - Operating Systems Spring 2008 Lecture - XII Midterm Review Tevfik Ko!ar Louisiana State University March 4 th, 2008 1 I/O Structure After I/O starts, control returns to user program only upon

More information

Multithreading Pearson Education, Inc. All rights reserved.

Multithreading Pearson Education, Inc. All rights reserved. 1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads

More information