Thread in Java - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

Thread in Java

Description:

You can use the method sleep( ) to stop the running state of a thread. ... This method and join(long millisec) Throws InterruptedException are invoked on a ... – PowerPoint PPT presentation

Number of Views:807
Avg rating:3.0/5.0
Slides: 25
Provided by: cisF
Category:
Tags: java | thread

less

Transcript and Presenter's Notes

Title: Thread in Java


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
  • New state the thread is considered
  • not alive.
  • Runnable (Ready-to-run) state
  • A thread start its life. On this state a
    thread is waiting for a turn on the processor. 
  • 3. Running state the thread is
  • currently executing
  • 4. Dead state its run() method completes.
  • 5. Blocked is waiting the resources that are
    hold by another 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 snull   
  • MyThread10(String s1)    
    ss1    tnew Thread(this)    t.start()   
     public void run()      System.out.println(s) 
        public class RunableThread  public stati
    c void main(String args)    MyThread10 m1new 
    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  Threa
    d t  MyThread11(String s)      tnew Thread(th
    is,s)    t.start()     public void run()  
        for(int i0ilt5i)       System.out.printl
    n("Thread Name  "Thread.currentThread().getName(
    ))      try       Thread.sleep(1000)      c
    atch(Exception e)      public class Runna
    bleThread1
  •  public static void main(String args)    
      System.out.println("Thread Name "Thread.curren
    tThread().getName())       MyThread11 m1new MyT
    hread11("My Thread 1")    MyThread11 m2new MyTh
    read11("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  MyThrea
    d12(String s)    super(s)    start()    pu
    blic void run()    for(int i0ilt3i)      T
    hread curThread.currentThread()      cur.setPri
    ority(Thread.MIN_PRIORITY)      int pcur.getPri
    ority()      System.out.println("Thread Name  "
    Thread.currentThread().getName())      System.o
    ut.println("Thread Priority  "cur)        
      class MyThread22 extends Thread  MyThread22(
    String s)    super(s)    start()  public 
    void run()    for(int i0ilt3i)      Thread
     curThread.currentThread()      cur.setPriority
    (Thread.MAX_PRIORITY)      int pcur.getPriority
    ()      System.out.println("Thread Name  "Thre
    ad.currentThread().getName())      System.out.pr
    intln("Thread Priority  "cur)        pub
    lic class ThreadPriority  public static void mai
    n(String args)      MyThread12 m1new MyThread
    12("My Thread 1")    MyThread22 m2new MyThread2
    2("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 threa
    dN)    for(int i0ilt4i)      System.out.pr
    intln(threadNmsgi)      try      this.sleep
    (1000)  catch(Exception e)    public cla
    ss SynThread1   public static void main(String
     args)       Share t1new Share("Thread One ")
        t1.start()    Share t2new Share("Thread Tw
    o ")    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  i
    nt val20  public static void main(String args
    )      DemoWait dnew DemoWait()    d.start()
        new Demo1(d)    public void run()    tr
    y        synchronized(this)    wait()    Sys
    tem.out.println("value is  "val)            
    catch(Exception e)   public void valchange(
    int val)        this.valval        try     
       synchronized(this)        notifyAll()      
         catch(Exception e)  class Demo1 ex
    tends Thread  DemoWait d  Demo1(DemoWait d)  
      this.dd  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   publi
    c void run()     System.out.println("Entering ru
    n method")    try       System.out.println("I
    n run Method currentThread() is"           Thre
    ad.currentThread())      while (true)        
     try           Thread.sleep(500)         catc
    h (InterruptedException x)                 Sy
    stem.out.println("In run method woke up again")
               finally       System.out.println("
    Leaving run Method")        public static vo
    id main(String args)     System.out.println("E
    ntering main Method")    DaemonThread t  new D
    aemonThread()    t.setDaemon(true)    t.start(
    )    try       Thread.sleep(3000)     catc
    h (InterruptedException x)         System.out
    .println("Leaving main method")  

23
Questions
  • ?

24
Reference
  • http//www.bpurcell.org/blog/index.cfm?modeentry
    ENTRY934
  • http//www.javaprepare.com/notes/threads.html
  • http//www.roseindia.net/java/thread/index.shtml
Write a Comment
User Comments (0)
About PowerShow.com