260 likes | 554 Views
Outline. What is Thread?Introduction (life circle, Method)Thread priority (with example)Thread creation (with example)Scheduler (with example)Synchronization (with example)Monitor (with example)Daemon (with example). What is a thread?. A thread is a lightweight processwhich exist within a p
E N D
1. Thread in Java Lang Zhao
COP5614
4/14/2008
2. Outline What is Thread?
Introduction (life circle, Method)
Thread priority (with example)
Thread creation (with example)
Scheduler (with example)
Synchronization (with example)
Monitor (with example)
Daemon (with example)
3. What is a thread? A thread is a lightweight process
which exist within a program and
executed to perform a special task.
Several threads of execution may be
associated with a single process.
4. Introduction In Java programming language
thread is a sequential path of code execution within a program.
the ‘thread’ class is defined in the package java.lang, which needs to be imported
5. Life circle of one thread
6. Life circle of multiple-threads
7. Life circle of multiple-threads non-runnable states:
Sleeping: the thread is still alive but it is not runnable. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread.
Waiting for Notification: A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread.
Blocked on I/O: waiting I/O resource, the thread sends back to runnable state after availability of resources.
Blocked for joint completion: waiting the completion of another thread.
Blocked for lock acquisition: waiting to acquire the lock of an object.
8. Some Important Methods defined in java.lang.Thread
9. Some Important Methods defined in java.lang.Thread
10. Thread Creation Two ways:
Extending the java.lang.Thread Class
Implementing the java.lang.Runnable Interface
11. Prefer for Implementing a Runnable Interface Two reasons:
If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this.
The class implementing the Runnable interface can avoid the full overhead of Thread class which can be excessive.
Example:
class MyThread10 implements Runnable{ Thread t; String s=null;
MyThread10(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s); }}public class RunableThread{ public static void main(String args[]){ MyThread10 m1=new MyThread10("Thread started...."); }}
12. Multiple-threads Advantages:
Reduces the computation time.
Improves performance of an application.
Threads share the same address space so it saves the memory.
Context switching between threads is usually less expensive than between processes.
Cost of communication between threads is relatively low.
13. Multiple-threads Creation Implementing a Runnable interface
class MyThread11 implements Runnable{ Thread t; MyThread11(String s) { t=new Thread(this,s); t.start(); } public void run() { for(int i=0;i<5;i++) { System.out.println("Thread Name :"+Thread.currentThread().getName()); try { Thread.sleep(1000); }catch(Exception e){} } }}public class RunnableThread1{
public static void main(String args[]) { System.out.println("Thread Name :"+Thread.currentThread().getName()); MyThread11 m1=new MyThread11("My Thread 1"); MyThread11 m2=new MyThread11("My Thread 2"); }}
both threads are registered with the thread scheduler and the CPU
scheduler executes them one by one.
14. Thread Priorities In Java
The thread scheduler can use the thread priorities to determine the execution schedule of threads .
2. The thread scheduler provides the CPU time to thread of highest
priority during ready-to-run state.
3. Priorities are integer values
Thread.MIN_PRIORITY: 1
Thread.MAX_PRIORITY: 10
Thread.NORM_PRIORITY: 5
15. Example of set priority class MyThread12 extends Thread{ MyThread12(String s){ super(s); start(); } public void run(){ for(int i=0;i<3;i++){ Thread cur=Thread.currentThread(); cur.setPriority(Thread.MIN_PRIORITY); int p=cur.getPriority(); System.out.println("Thread Name :"+Thread.currentThread().getName()); System.out.println("Thread Priority :"+cur); } }} class MyThread22 extends Thread{ MyThread22(String s){ super(s); start(); }public void run(){ for(int i=0;i<3;i++){ Thread cur=Thread.currentThread(); cur.setPriority(Thread.MAX_PRIORITY); int p=cur.getPriority(); System.out.println("Thread Name :"+Thread.currentThread().getName()); System.out.println("Thread Priority :"+cur); } }}public class ThreadPriority{ public static void main(String args[]){ MyThread12 m1=new MyThread12("My Thread 1"); MyThread22 m2=new MyThread22("My Thread 2"); }}
16. Thread Scheduler Preemptive scheduling: In Java runtime system, if the new thread has a higher priority, the current running thread leaves the runnable state and higher priority thread enter to the runnable state.
Time-Sliced (Round-Robin) Scheduling: if two threads of the same priority are waiting to be executed by the cpu. A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.
17. Synchronization Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
All methods in a class need not to be synchronized. A class can have both synchronized and non-synchronized methods.
If two threads wants to execute a synchronized method in a class, and both threads are using the same instance of the class to invoke the method then only one thread can execute the method at a time.
If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods. If you have methods that don't access the data you're trying to protect, then you don't need to synchronize them. Synchronization can cause a hit in some cases (or even deadlock if used incorrectly), so you should be careful not to overuse it.
You can synchronize a block of code rather than a method.
Constructors cannot be synchronized
18. Synchronized Method of Threads class Share extends Thread{ static String msg[]={"This", "is", "a", "synchronized", "variable"}; Share(String threadname){ super(threadname); } public void run(){ display(getName()); } public synchronized void display(String threadN){ for(int i=0;i<=4;i++) System.out.println(threadN+msg[i]); try{ this.sleep(1000); }catch(Exception e){} }}public class SynThread1 { public static void main(String[] args) { Share t1=new Share("Thread One: "); t1.start(); Share t2=new Share("Thread Two: "); t2.start();}}
19. Monitor Monitor is any class with synchronized code in it.
Monitor controls its client threads using wait() and notify() ( or notifyAll() ) methods.
wait() and notify() methods must be called in synchronized code.
Monitor asks client threads to wait if it is unavailable.
Normally a call to wait() is placed in while loop. The condition of while loop generally tests the availability of monitor. After waiting, thread resumes execution from the point it left.
20. Example of Monitor public class DemoWait extends Thread{ int val=20; public static void main(String args[]) { DemoWait d=new DemoWait(); d.start(); new Demo1(d); } public void run(){ try { synchronized(this){ wait(); System.out.println("value is :"+val); } }catch(Exception e){} } public void valchange(int val){ this.val=val; try { synchronized(this) { notifyAll(); } }catch(Exception e){} }}class Demo1 extends Thread{ DemoWait d; Demo1(DemoWait d) { this.d=d; start(); } public void run(){ try{ System.out.println("Demo1 value is: "+d.val); d.valchange(40); }catch(Exception e){} }}
21. Daemon In Java,
any thread can be a Daemon thread.
Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread.
Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.
If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
22. Example of Daemon public class DaemonThread extends Thread { public void run() { System.out.println("Entering run method"); try { System.out.println("In run Method: currentThread() is" + Thread.currentThread()); while (true) { try { Thread.sleep(500); } catch (InterruptedException x) { } System.out.println("In run method: woke up again"); } } finally { System.out.println("Leaving run Method"); } } public static void main(String[] args) { System.out.println("Entering main Method"); DaemonThread t = new DaemonThread(); t.setDaemon(true); t.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("Leaving main method"); }}
23. Questions ?
24. Reference http://www.bpurcell.org/blog/index.cfm?mode=entry&ENTRY=934
http://www.javaprepare.com/notes/threads.html
http://www.roseindia.net/java/thread/index.shtml