0% found this document useful (0 votes)
103 views27 pages

Java Threads

This document provides information about Java threads including tutorials, the Thread class, techniques for creating threads by implementing Runnable or extending Thread, thread scheduling and priority, synchronization using synchronized methods/blocks and wait/notify, and examples of thread usage.

Uploaded by

swethaTMR
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
103 views27 pages

Java Threads

This document provides information about Java threads including tutorials, the Thread class, techniques for creating threads by implementing Runnable or extending Thread, thread scheduling and priority, synchronization using synchronized methods/blocks and wait/notify, and examples of thread usage.

Uploaded by

swethaTMR
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 27

Java Threads

Resources
Java Threads by Scott Oaks & Henry Wong (OReilly) API docs
http://download.oracle.com/javase/6/docs/api/ java.lang.Thread, java.lang.Runnable java.lang.Object, java.util.concurrent

Tutorials
http://download.oracle.com/javase/tutorial/essential/concurrency/index.html http://download.oracle.com/javase/tutorial/essential/concurrency/procthread.html

Introduction to Java Threads


http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html

Thread safety
http://en.wikipedia.org/wiki/Thread-safety

http://www.javaworld.com/jw-08-1998/jw-08-techniques.html
1

Coverage
Thread class
run, start methods yield, join sleep

Synchronization
synchronized methods & objects wait/notify/notifyAll conditions
2

java.lang.Thread
Two techniques to create threads in java 1) implementing the Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method, called run, with no arguments. invoke Thread constructor with an instance of this Runnable class See pages 162 and 164 in text for an example

2) extending Thread
Define a subclass of java.lang.Thread
Define a run method

In another thread (e.g., the main), create an instance of the Thread subclass
Then, call start method of that instance
3

Example 1
Create 2 threads from the Main, then start them Threads will be instances of different thread sub-classes

class MyThreadA extends Thread { public void run() { // entry point for thread for (;;) { System.out.println("hello world1"); } } }

class MyThreadB extends Thread { public void run() { // entry point for thread for (;;) { System.out.println("hello world2"); } } }
public class Main1 { public static void main(String [] args) { MyThreadA t1 = new MyThreadA(); MyThreadB t2 = new MyThreadB(); t1.start(); t2.start();
// main terminates, but in Java the other threads keep running // and hence Java program continues running

} }
5

hello world2 hello world2 hello world1 hello world2 hello world1 hello world2 hello world2 hello world1 hello world1 hello world1 hello world1 hello world2 hello world1 hello world1 hello world2 hello world2 hello world1 hello world1 hello world2 hello world2 hello world1 hello world1 hello world2

Example 2
Create 2 threads from the Main, then start them Threads will be instances of the same thread sub-class Use argument of constructor of new thread class to pass text name of thread, e.g., thread1 and thread2
Data member provides different data per thread (i.e., then name) A data member can also be used to share data
7

class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; }

public void run() { for (;;) { System.out.println(name + ": hello world"); } }


} public class Main2 { public static void main(String [] args) { MyThread t1 = new MyThread("thread1"); MyThread t2 = new MyThread("thread2"); t1.start(); t2.start(); } }
8

thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread2: hello world thread1: hello world thread2: hello world thread2: hello world

See the variation in output: This variation in output is called a race condition (often race conditions are bugs in programs)

java.lang.Thread
public static void yield();
Method of java.lang.Thread Thread gives up CPU for other threads ready to run

10

class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; }

public void run() { for (;;) { System.out.println(name + ": hello world"); yield(); } }
} public class Main3 { public static void main(String [] args) { MyThread t1 = new MyThread("thread1"); MyThread t2 = new MyThread("thread2"); t1.start(); t2.start(); } }

11

thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world

Some Output

Notice the alternation of output


12

More Thread Members: join


public final void join();
MyThread t1 = new MyThread("thread1"); t1.start(); t1.join(); Wait until the thread is not alive Threads that have completed are not alive as are threads that have not yet been started
public static void sleep (long millis) throws InterruptedException;
Makes the currently running thread sleep (block) for a period of time The thread does not lose ownership of any monitors. InterruptedException - if another thread has interrupted the current thread.
13

Join Example

14

hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 Thread is done!

Some output

15

Thread State
public Thread.State getState()
Returns the state of this thread. This method is designed for use in monitoring of the system state, not for synchronization control

http://java.sun.com/javase/6/docs/api/java/lang/Thread.State.html

Thread Scheduling in Java


public final void setPriority(int newPriority); public final int getPriority(); public static final int MAX_PRIORITY
// on my system: 10; Mac OS X 2/21/05

public static final int MIN_PRIORITY


// on my system: 1; Mac OS X 2/21/05

Scheduling
Priority inherited from parent, but can be changed Higher priority threads generally run before lower priority threads For equal priority threads, best to call yield() intermittently to handle JVMs with user-level threading (i.e., no time-slicing)

17

Basic Tools for Synchronization in Java


Synchronized methods Synchronized objects Methods
wait notify notifyAll

Also should talk about condition variables in Java

18

Synchronized Methods: Monitors


synchronized keyword used with a method
E.g.,
public synchronized void SetValue() { // Update instance data structure. // When the thread executes here, it exclusively has the monitor lock }

Provides instance-based mutual exclusion


A lock is implicitly provided-- allows at most one thread to be executing the method at one time

Used on a per method basis; not all methods in a class have to have this
But, youll need to design it right!!
19

Difference: Synchronized vs. Non-synchronized


Class with synchronized methods
How many threads can access the methods of an object?

Class with no synchronized methods


How many threads can access the methods of an object?

20

wait method (see also java.lang.Object)


Does a blocking (not busy) wait Relative to an Object
E.g., Used within a synchronized method

Releases lock on Object and waits until a condition is true


Blocks calling process until notify() or notifyAll() is called on same object instance (or exception occurs)

Typically used within a loop to re-check a condition wait(long millis); // bounded wait

21

notify and notifyAll methods (see also java.lang.Object)


Stop a process from waiting wakes it up Relative to an Object
E.g., Used within a synchronized method

Wakes up a blocked thread (notify) or all blocked threads (notifyAll)


One woken thread reacquires lock; The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object.

For notify, if more than one thread available to be woken, then one is picked

22

InterruptedException
Wait can be woken by the exception, I.e., for reasons other than notify Sometimes this can be handled as part of the process of re-checking conditions There is another way to handle it too

23

Synchronized Blocks
Synchronized methods
Implicitly lock is on this object

Synchronized blocks
lock on an arbitrary, specified object similar to condition variables in monitors but need to have a synchronized block around an object before wait/notify used use wait/notify on the object itself
24

Syntax
synchronized (object) { // object.wait() // object.notify() // object.notifyAll() } For example, this allows you to synchronize just a few lines of code, or to synchronize on the basis of an arbitrary object
25

public class Deadlock { public static void main(String[] args) { // These are the two resource objects we'll try to get locks for final Object resource1 = "resource1"; final Object resource2 = "resource2"; // Here's the first thread. It tries to lock resource1 then resource2 Thread t1 = new Thread() { public void run() { // Lock resource 1 synchronized(resource1) { System.out.println("Thread 1: locked resource 1"); try { Thread.sleep(50); } catch (InterruptedException e) {} // Now wait 'till we can get a lock on resource 2 synchronized(resource2) { System.out.println("Thread 1: locked resource 2"); } } } };

// Here's the second thread. It tries to lock resource2 then resource1 Thread t2 = new Thread() { public void run() { // This thread locks resource 2 right away synchronized(resource2) { System.out.println("Thread 2: locked resource 2"); // Then it pauses, for the same reason as the first thread does try { Thread.sleep(50); } catch (InterruptedException e) {} synchronized(resource1) { System.out.println("Thread 2: locked resource 1"); } } } }; t1.start(); t2.start(); } }

You might also like