Presentation is loading. Please wait.

Presentation is loading. Please wait.

Multi-Threading in Java

Similar presentations


Presentation on theme: "Multi-Threading in Java"— Presentation transcript:

1 Multi-Threading in Java

2 Thread Thread: a flow of control in a program In Java,
Process: a running instance of a program including all variables and other states In Java, Application: the Java interpreter starts a thread for the main method. Applet: the Web browser starts a thread to run the applet. Java has built-in support for multi-threading.

3 A typical program Multi-Thread Start Task1 Task2 Task1 Task2 Task3
Stop Stop

4 Multi-Threading Multi-threading is the capability of running multiple tasks concurrently within a program. Multi-threading can make your program more responsive and interactive, and run faster than a non-threaded version. Issues Prioritization Synchronization

5 Creating Thread Thread class Example
Extend Thread class and override the run method Example class SimpleThread extends Thread {             public void run() {             // work for thread           }        } SimpleThread t = new SimpleThread () ;// create thread t.start(); // begin running thread

6 Runnable interface Example
Create object implementing Runnable interface Pass it to Thread object via Thread constructor Example class SimpleThread extends Frame implements Runnable {             public void run() {             // work for thread           }        } Thread t = new Thread(new SimpleThread()); // create thread t.start(); // begin running thread

7 Life cycle of Thread new start new ready I/O complete, time-out,
notify, resume yield (dispatch) running blocked Yield --- a thread may be in queing status which is controlled by java runtime scheduler. I/O, sleep, wait, suspend terminate dead

8 Overview of the Thread Methods
run():void start():void – to make a Thread eligible for use sleep():void – to make a Thread inactive interrupt():void – to interrupt a running Thread isAlive():boolean – to check status of a Thread Other methods Stop(), setPriority(p: int), wait(), notify()…

9 Examples MyThread PriThread Show simple multi-threading
Use the method setPriority(p: int)

10 Thread Synchronization
To avoid resource conflicts, may synchronize method invocation so that only one thread can access a method at a time. Keyword synchronized Only one thread at a time to execute statements within synchronized blocks. All other threads block until the method finishes. If several synchronized statements are trying to execute on an object at the same time, only one of them is active on the object. Example: ConcurrenyDemo


Download ppt "Multi-Threading in Java"

Similar presentations


Ads by Google