1 / 24

Thread in Java

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

nico
Télécharger la présentation

Thread in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    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: classMyThread10implementsRunnable{ Threadt; String s=null; MyThread10(Strings1){ s=s1; t=newThread(this); t.start(); } publicvoidrun(){ System.out.println(s); } } publicclassRunableThread{ publicstaticvoidmain(Stringargs[]){ MyThread10m1=newMyThread10("Threadstarted...."); } }

    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 classMyThread11implementsRunnable{ Threadt; MyThread11(Strings){ t=newThread(this,s); t.start(); } publicvoidrun(){ for(inti=0;i<5;i++){ System.out.println("ThreadName:"+Thread.currentThread().getName()); try{ Thread.sleep(1000); }catch(Exceptione){} } } } publicclassRunnableThread1{ publicstaticvoidmain(Stringargs[]){ System.out.println("ThreadName:"+Thread.currentThread().getName()); MyThread11m1=newMyThread11("MyThread1"); MyThread11m2=newMyThread11("MyThread2"); } } 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 classMyThread12extendsThread{ MyThread12(Strings){ super(s); start(); } publicvoidrun(){ for(inti=0;i<3;i++){ Threadcur=Thread.currentThread(); cur.setPriority(Thread.MIN_PRIORITY); intp=cur.getPriority(); System.out.println("ThreadName:"+Thread.currentThread().getName()); System.out.println("ThreadPriority:"+cur); } } } classMyThread22extendsThread{ MyThread22(Strings){ super(s); start(); } publicvoidrun(){ for(inti=0;i<3;i++){ Threadcur=Thread.currentThread(); cur.setPriority(Thread.MAX_PRIORITY); intp=cur.getPriority(); System.out.println("ThreadName:"+Thread.currentThread().getName()); System.out.println("ThreadPriority:"+cur); } } } publicclassThreadPriority{ publicstaticvoidmain(Stringargs[]){ MyThread12m1=newMyThread12("MyThread1"); MyThread22m2=newMyThread22("MyThread2"); } }

    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 classShareextendsThread{ staticStringmsg[]={"This","is","a","synchronized","variable"}; Share(Stringthreadname){ super(threadname); } publicvoidrun(){ display(getName()); } publicsynchronizedvoiddisplay(StringthreadN){ for(inti=0;i<=4;i++) System.out.println(threadN+msg[i]); try{ this.sleep(1000); }catch(Exceptione){} } } publicclassSynThread1{ publicstaticvoidmain(String[]args){ Sharet1=newShare("ThreadOne:"); t1.start(); Sharet2=newShare("ThreadTwo:"); 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 publicclassDemoWaitextendsThread{ intval=20; publicstaticvoidmain(Stringargs[]){ DemoWaitd=newDemoWait(); d.start(); newDemo1(d); } publicvoidrun(){ try{ synchronized(this){ wait(); System.out.println("valueis:"+val); } }catch(Exceptione){} } publicvoidvalchange(intval){ this.val=val; try{ synchronized(this){ notifyAll(); } }catch(Exceptione){} } } classDemo1extendsThread{ DemoWaitd; Demo1(DemoWaitd){ this.d=d; start(); } publicvoidrun(){ try{ System.out.println("Demo1valueis: "+d.val); d.valchange(40); }catch(Exceptione){} } }

    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 publicclassDaemonThreadextendsThread{ publicvoidrun(){ System.out.println("Enteringrunmethod"); try{ System.out.println("InrunMethod:currentThread()is" +Thread.currentThread()); while(true){ try{ Thread.sleep(500); }catch(InterruptedExceptionx){ } System.out.println("Inrunmethod:wokeupagain"); } }finally{ System.out.println("LeavingrunMethod"); } } publicstaticvoidmain(String[]args){ System.out.println("EnteringmainMethod"); DaemonThreadt=newDaemonThread(); t.setDaemon(true); t.start(); try{ Thread.sleep(3000); }catch(InterruptedExceptionx){ } System.out.println("Leavingmainmethod"); } }

    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

More Related