Title: Tutorial:%20CSI%203310
1Tutorial CSI 3310
- Dewan Tanvir Ahmed
- SITE, UofO
2Todays Objective
- What is a Thread?
- A thread is a single sequential flow of control
within a program.
3multithread
4The lifecycle of a thread
5Class Thread
- java.lang.Thread
- Constructors
- public Thread()
- Allocates a new Thread object.
- Automatically generated names are of the form
"Thread-"n, where n is an integer. - public Thread(Runnable target)
- target - the object whose run method is called.
- 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 of no arguments
called run. - public Thread(String threadName)
- public Thread(Runnable target, String threadName)
6Methods of Class Thread
- public void start()
- Causes this thread to begin execution
- the Java Virtual Machine calls the run method of
this thread. - The result is that two threads are running
concurrently the current thread (which returns
from the call to the start method) and the other
thread (which executes its run method). - public void run()
- If this thread was constructed using a separate
Runnable run object, then that Runnable object's
run method is called - otherwise, this method does nothing and returns.
- Subclasses of Thread should override this method.
7Methods of Class Thread
- public static void sleep(long milliseconds)
throws InterruptedException - Causes the currently executing thread to sleep
(temporarily cease execution) for the specified
number of milliseconds. The thread does not lose
ownership of any monitors. - try
- Thread.sleep(1000)
- catch (InterruptedException e)
-
-
8Create a thread (1)
- extend the class Thread and override the run()
method - Example
- class Test extends Thread
- public void run()
-
- public static void main(String args)
-
- Test t new Test ()
- t.start()
-
9Pure example
- class MyThread1 extends Thread
- static String message "Java","is","hot,","ar
omatic,","and","invigorating." -
- public MyThread1(String id)
- super(id)
-
- public void run()
- String name getName()
- for(int i0 iltmessage.lengthi)
- randomWait()
- System.out.println(namemessagei)
-
-
- void randomWait()
- try
- sleep((long)(1000Math.random()))
- catch (InterruptedException x)
- System.out.println("Interrupted!")
-
10example (cont)
- public static void main(String args)
- MyThread1 thread1 new MyThread1("thread1 ")
- MyThread1 thread2 new MyThread1("thread2 ")
- thread1.start()
- thread2.start()
- boolean thread1IsAlive true
- boolean thread2IsAlive true
- do
- if(thread1IsAlive !thread1.isAlive())
- thread1IsAlive false
- System.out.println("Thread 1 is dead.")
-
- if(thread2IsAlive !thread2.isAlive())
- thread2IsAlive false
- System.out.println("Thread 2 is dead.")
-
- while(thread1IsAlive thread2IsAlive)
-
11results
thread1 Java thread2 Java thread1 is thread1 hot, thread2 is thread1 aromatic, thread2 hot, thread1 and thread2 aromatic, thread1 invigorating. Thread 1 is dead. thread2 and thread2 invigorating. Thread 2 is dead. thread2 Java thread1 Java thread1 is thread2 is thread2 hot, thread2 aromatic, thread2 and thread2 invigorating. Thread 2 is dead. thread1 hot, thread1 aromatic, thread1 and thread1 invigorating. Thread 1 is dead. thread1 Java thread1 is thread1 hot, thread1 aromatic, thread2 Java thread1 and thread1 invigorating. Thread 1 is dead. thread2 is thread2 hot, thread2 aromatic, thread2 and thread2 invigorating. Thread 2 is dead.
12Interface Runnable
- java.lang.Runnable
- 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 of no arguments
called run. - Runnable provides the means for a class to be
active while not subclassing Thread. - A class that implements Runnable can run without
subclassing Thread by instantiating a Thread
instance and passing itself in as the target. - In most cases, the Runnable interface should be
used if you are only planning to override the
run() method and no other Thread methods. This is
important because classes should not be
subclassed unless the programmer intends on
modifying or enhancing the fundamental behavior
of the class. - Method
- public void run()
13Runnable Interface
- Multithreading in a class that extends a class
- A class cannot extend more than one class
- Implements Runnable for multithreading support
- Runnable object grouped with a Thread object
14Create a thread (2)
- implement the Runnable interface
- class Test implements Runnable
- public void run()
-
- public static void main(String args)
-
- Test t new Test ()
- Thread th new Thread(t)
- th.start()
-
15Pure example
- class MyThread2
- public static void main(String args)
- Thread thread1 new Thread(new
MyClass("thread1 ")) - Thread thread2 new Thread(new
MyClass("thread2 ")) - thread1.start()
- thread2.start()
- boolean thread1IsAlive true
- boolean thread2IsAlive true
- do
- if(thread1IsAlive !thread1.isAlive())
- thread1IsAlive false
- System.out.println("Thread 1 is dead.")
-
- if(thread2IsAlive !thread2.isAlive())
- thread2IsAlive false
- System.out.println("Thread 2 is dead.")
-
- while(thread1IsAlive thread2IsAlive)
-
16example (cont)
- class MyClass implements Runnable
- static String message "Java","is","hot,","ar
omatic,","and","invigorating." - String name
- public MyClass(String id)
- name id
-
- public void run()
- for(int i0 iltmessage.lengthi)
- randomWait()
- System.out.println(namemessagei)
-
-
- void randomWait()
- try
- Thread.currentThread().sleep((long)(3000Math.r
andom())) - catch (InterruptedException x)
- System.out.println("Interrupted!")
-
-
17results
thread1 Java thread2 Java thread1 is thread1 hot, thread2 is thread1 aromatic, thread2 hot, thread1 and thread1 invigorating. Thread 1 is dead. thread2 aromatic, thread2 and thread2 invigorating. Thread 2 is dead. thread2 Java thread1 Java thread2 is thread1 is thread2 hot, thread2 aromatic, thread1 hot, thread1 aromatic, thread2 and thread2 invigorating. Thread 2 is dead. thread1 and thread1 invigorating. Thread 1 is dead. thread1 Java thread2 Java thread2 is thread2 hot, thread2 aromatic, thread1 is thread1 hot, thread2 and thread1 aromatic, thread2 invigorating. Thread 2 is dead. thread1 and thread1 invigorating. Thread 1 is dead.
18example
- import java.io.
- import java.lang.
- import java.lang.Thread.
- class Processus extends Thread
- static int mem
- Processus(String name)
- super() // call of the super class constructor
(Thread) - setName(name) // setting the name
-
- / redefinition of the run() method /
- public void run()
- for(int i0 ilt10 i)
- System.out.println(getName()"("i")
"(mem)) - try
- sleep((int)(Math.random()1000))
- catch(InterruptedException x)
- System.out.println("Thread "getName()"interrup
ted !") -
19example
- import java.io.
- import java.lang.
- class TestProc
- public static void main(String args)
- Processus p1 new Processus("p1")
- Processus p2 new Processus("p2")
- Processus p3 new Processus("p3")
-
- p1.start()
- p2.start()
- p3.start()
- for(int i0 ilt10 i)
- System.out.println("main("i")")
-
-
20example
- import java.io.
- import java.lang.
- class ThreadRunnable implements Runnable
- static int mem
- Thread T
- ThreadRunnable(String name)
- T new Thread(this) // creation of a new
Thread - setName(name) // setting of the name
-
- public void run()
- for(int i0 ilt10 i)
- System.out.println(getName()"("i")
"(mem)) - try T.sleep((int)Math.random()1000)
- catch(InterruptedException e)
System.out.println("Sleep interrupted !") -
-
- public void start()
- T.start()
-
21example
- import java.io.
- import java.lang.
- class TestRunnable
- public static void main(String args)
- ThreadRunnable p1 new ThreadRunnable("p1")
- ThreadRunnable p2 new ThreadRunnable("p2")
- ThreadRunnable p3 new ThreadRunnable("p3")
- p1.start()
- p2.start()
- p3.start()
- for(int i0 ilt10 i)
- System.out.println("main("i")")
-
-
22Methods are deprecated
- suspend()
- Forces the thread to stop executing.
- resume()
- Resumes a suspended thread.
- stop()
- Forces the thread to stop executing.
- Unsafe
- Cause the data lose or deadlock
23Instead of stop()
- stop()
- replaced by code that simply modifies some
variable to indicate that the target thread
should stop running
24example
- Using stop()
- private Thread blinker
- public void start()
- blinker new Thread(this)
- blinker.start()
-
- public void stop()
- blinker.stop() // UNSAFE!
-
25Example(cont)
- public void run()
- Thread thisThread Thread.currentThread()
- while (true)
- try
- hisThread.sleep(interval)
- catch (InterruptedException e)
-
- repaint()
-
-
26example
- replacing the stop and run methods
- public void stop()
- blinker null
-
- public void run()
- Thread thisThread Thread.currentThread()
- while (blinker thisThread)
- try thisThread.sleep(interval)
- catch (InterruptedException e)
- repaint()
-
-
27Instead of suspend() and resume()
- suspend()
- wait()
- Causes current thread to wait until another
thread invokes the notify() method or the
notifyAll() method for this object. - The current thread must own this object's
monitor. - The thread releases ownership of this monitor and
waits until another thread notifies threads
waiting on this object's monitor to wake up
either through a call to the notify method or the
notifyAll method. - The thread then waits until it can re-obtain
ownership of the monitor and resumes execution. - This method should only be called by a thread
that is the owner of this object's monitor.
28Instead of suspend() and resume() cont..
- resume()
- notify()
- Wakes up a single thread that is waiting on this
object's monitor. - If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the
implementation. - A thread waits on an object's monitor by calling
one of the wait methods. - The awakened thread will not be able to proceed
until the current thread relinquishes the lock on
this object. The awakened thread will compete in
the usual manner with any other threads that
might be actively competing to synchronize on
this object for example, the awakened thread
enjoys no reliable privilege or disadvantage in
being the next thread to lock this object.
29Thread priority
- A thread's priority affects when it runs in
relation to other threads - MIN_PRIORITY(1)
- MAX_PRIORITY(10)
- NORM_PRIORITY (5) - default
30Thread priority
- setPriority(int newPriority)
- Changes the priority of this thread
- getPriority()
- Returns this thread's priority
- yield()
- Causes the currently executing thread object to
temporarily pause and allow other threads to
execute
31priority scheduling
- From highest to lowest
- Same priority
- run in a round-robin fashion
- yield()
- preemptive
32priority scheduling
33Example
- import java.io.
- public class PriorityTest
- static int NUM_THREADS 4
- static final int MAX_COUNTER 2000000
- static boolean yield true
- static int counter new intNUM_THREADS
- public static void main (String args)
- PrintWriter out new PrintWriter
(System.out, true) - int numIntervals 10
- if (args.length gt 0)
- yield false
- out.println ("Using yield()? " (yield ?
"YES" "NO")) - for (int i 0 i lt NUM_THREADS i)
- (new PrTestThread ((i gt 1) ? 4 (i 1),
i)).start() - ThreadInfo.printAllThreadInfo()
- out.println()
34Example(cont)
- // repeatedly print out the counter values
- int step 0
- while (true)
- boolean allDone true
- try
- Thread.sleep (300)
- catch (InterruptedException e)
-
- out.print ("Step " (step) "
COUNTERS") - for (int j 0 j lt NUM_THREADS j)
- out.print (" " counterj)
- if (counterj lt MAX_COUNTER)
- allDone false
-
- out.println()
- if (allDone)
- break
-
- System.exit(0)
35Example(cont)
- class PrTestThread extends Thread
- int id
- PrTestThread (int priority, int id)
- super ("PrTestThread" id)
- this.id id
- setPriority(priority)
-
- public void run()
- for (int i 0 i lt PriorityTest.MAX_COUNTER
i) - if (((i 3000) 0) PriorityTest.yield)
- yield()
- PriorityTest.counterid i
-
-
36Thread Synchronization
- Java uses monitors for thread synchronization
- The sychronized keyword
- Every synchronized method of an object has a
monitor - One thread inside a synchronized method at a time
- All other threads block until method finishes
- Next highest priority thread runs when method
finishes
37Producer/Consumer Relationship without
Synchronization
- Buffer
- Shared memory region
- Producer thread
- Calls produce method to add item to buffer
- Calls wait if consumer has not read last message
in buffer - Writes to empty buffer and calls notify for
consumer - Consumer thread
- Reads message from buffer
- Calls wait if buffer empty
- Synchronize threads to avoid corrupted data
38Thank You!