Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Based Techhnology

Similar presentations


Presentation on theme: "Java Based Techhnology"— Presentation transcript:

1 Java Based Techhnology
Java Threads 12/27/2018 Java thread Applications

2 Java thread Applications
Introductions Java defines a model of concurrency and synchronization and is thus a concurrent object-oriented language. The unit of concurrency is a thread. A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. 12/27/2018 Java thread Applications

3 Java thread Applications
Introductions Threads are a way for a program to fork or split itself into two or more simultaneously running tasks. On a single processor, Multithreading occurs by time-division multiplexing (time slicing); The processor switches between different threads. On a multiprocessor or multi-core system, multiple threads can run simultaneously on different processors or cores 12/27/2018 Java thread Applications

4 Java thread Applications
Introductions A thread executes statements and moves from object to object as it executes method invocations. Threads can be dynamically created, pre-empted, suspended, resumed and terminated. Each thread belongs to a thread group specified at thread creation time 12/27/2018 Java thread Applications

5 Java thread Applications
Thread Creations Package java.lang.Thread 1 st Method Public class Thread extends Thread Runnable{ } 2nd Method Public class Thread implements Runnable { } 12/27/2018 Java thread Applications

6 Java thread Applications
It allows to perform more than one task at a time. Resource sharing between threads is easy. It maximizes CPU utilization It reduces the complexity of large programs. It increases the speed of execution. 12/27/2018 Java thread Applications

7 Java thread Applications
Examples class HelloThread extends Thread { public void run() { try{ for ( ; ; ) { System.out.println("hello"); sleep(1000); } }catch(Exception e){} } } public class ThreadTest { public static void main(String[] args) throws Exception { Thread hello = new HelloThread(); hello.start(); System.out.println("Sorry, I must be leaving"); } } 12/27/2018 Java thread Applications

8 Java thread Applications
Thread States 12/27/2018 Java thread Applications

9 Java thread Applications
Thread States New Thread  Creates a new thread but does not start it, hereby leaving the thread in the New Thread state. Exp: Thread myThread = new MyThreadClass(); Runnable Exp:Thread myThread = new MyThreadClass();myThread.start(); The start method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread's run method. At this point the thread is in the "Runnable" state. 12/27/2018 Java thread Applications

10 Java thread Applications
Thread States Not Runnable  Someone invokes its sleep method. Someone invokes its suspend method. The thread uses its wait method to wait on a condition variable. The thread is blocking on I/O. Dead A thread can die in two ways: either from natural causes, or by being killed (stopped). A thread dies naturally when its run method exits normally. 12/27/2018 Java thread Applications

11 Java thread Applications
Thread States Example Thread myThread = new MyThreadClass(); myThread.start(); try { Thread.sleep(10000); } catch (InterruptedException e) {} myThread.stop(); 12/27/2018 Java thread Applications

12 Java thread Applications
Simple Program public class Threads{   public static void main(String[] args){   Thread th = new Thread();   System.out.println("Numbers are printing line by line after 5 seconds : ");   try{   for(int i = 1;i <= 10;i++)     {   System.out.println(i);   th.sleep(5000);   }   }   catch(InterruptedException e){     System.out.println("Thread interrupted!");   e.printStackTrace();   }   } } 12/27/2018 Java thread Applications

13 Java thread Applications
Life Cycles Of Thread 12/27/2018 Java thread Applications

14 Java thread Applications
Life Cycles Of Thread New state – after the Thread creation it is in this state but before the start() method invocation. ( thread is considered not alive)       Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.  12/27/2018 Java thread Applications

15 Java thread Applications
Life Cycles Of Thread Running state – Is currently executing. The scheduler select a thread from runnable pool.       Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. Blocked – A thread can enter in this state because of waiting the resources that are hold by another thread. 12/27/2018 Java thread Applications

16 Creation of Multithread
class MyThread extends Thread{   MyThread(String s){     super(s);     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 MultiThread1{   public static void main(String args[]){     System.out.println("Thread Name :"            +Thread.currentThread().getName());       MyThread m1=new MyThread("My Thread 1");     MyThread m2=new MyThread("My Thread 2");   } } 12/27/2018 Java thread Applications

17 Java thread Applications
Output C:\nisha>javac MultiThread1.java C:\nisha>java MultiThread1 Thread Name :main Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 12/27/2018 Java thread Applications

18 Using Runnable Interfaces
class MyThread1 implements Runnable{   Thread t;   MyThread1(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());       MyThread1 m1=new MyThread1("My Thread 1");     MyThread1 m2=new MyThread1("My Thread 2");   } } 12/27/2018 Java thread Applications

19 Java thread Applications
Thread Methods  Method  Return Type  Description  currentThread( )  Thread  Returns an object reference to the thread in which it is invoked.  getName( )  String  Retrieve the name of the thread object or instance.  start( )  void  Start the thread by calling its run method.  run( )  This method is the entry point to execute thread, like the main method for applications.  sleep( )  Suspends a thread for a specified amount of time (in milliseconds).   isAlive( )  boolean  This method is used to determine the thread is running or not. 12/27/2018 Java thread Applications

20 Java thread Applications
Thread Methods  Method  Return Type  Description  activeCount( )  int  Returns the number of active threads in a particular thread group and all its subgroups.  interrupt( )  void  Method interrupt the threads on which it is invoked.  yield( )  By invoking this method the current thread pause its execution temporarily and allow other threads to execute.  join( )  This method and  join(long millisecond) Throws Interrupted Exception.  These two methods are invoked on a thread, are not returned until either the thread has completed or it is timed out respectively. 12/27/2018 Java thread Applications

21 Java thread Applications
Java MultiThreading A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Is a specialized form of multitasking Types Process-based multitasking - allows your computer to run two or more programs concurrently Thread-based multitasking – Singleprogram can perform two or more tasks simultaneously 12/27/2018 Java thread Applications

22 Java thread Applications
Context switch Thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. Rules A thread can voluntarily relinquish control By explicitly yielding, sleeping,or blocking on pending I/O. Highest-priority thread that is ready to run is given CPU. A thread can be preempted by a higher-priority thread. Lower-priority thread that does not yield the processor is simply preempted—(no matter what it is doing—by a higher-priority thread.) Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. 12/27/2018 Java thread Applications

23 Java thread Applications
Examples // Controlling the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } } 12/27/2018 Java thread Applications

24 Java thread Applications
Thread Priorities Java assigns to each thread a priority that determines how that thread should be treated with respect to the others Thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads . Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.   12/27/2018 Java thread Applications

25 Java thread Applications
Thread Priorities Constant  Description  Thread.MIN_PRIORITY  The maximum priority of any thread (an int value of 10)  Thread.MAX_PRIORITY  The minimum priority of any thread (an int value of 1)  Thread.NORM_PRIORITY  The normal priority of any thread (an int value of 5) 12/27/2018 Java thread Applications

26 Thread Priorities Methods
 Description  setPriority()  This is method is used to set the priority of thread.  getPriority()  This method is used to get the priority of thread Example 12/27/2018 Java thread Applications

27 Java thread Applications
Priority Examples Example 1 Example2 Example3 12/27/2018 Java thread Applications

28 Thread Synchronization
In a multithreaded environment, each thread has its own local thread stack and registers. If multiple threads access the same resource for read and write, the value may not be the correct value. Synchronization stages Signaled allows objects to access and modify data Non-signaled. state does allow accessing or modifying the data in the thread local stack Syntax synchronized(objectidentifier) { // Access shared variables and other shared resources } 12/27/2018 Java thread Applications

29 Thread Synchronization
Java supports thread synchronization either by a synchronized method or by synchronized statement. Synchronization forces a thread to acquire a lock on an object before proceeding. If a thread already holds a lock on that object can continue. This avoids deadlocks- a thread reentering an object. 12/27/2018 Java thread Applications

30 Thread Synchronization methods
Event: Event is a thread synchronization object used to set the signaled or non-signaled state. Signaled state may be manual or automatic depending on the event declaration. Mutex: Mutex is the thread synchronization object which allows to access the resource only one thread at a time. Only when a process goes to the signaled state are the other resources allowed to access. Semaphore: Semaphore is a thread synchronization object that allows zero to any number of threads access simultaneously. 12/27/2018 Java thread Applications

31 Java thread Applications
DeadLock A situation where a thread is waiting for an object lock that holds by second thread, and this second thread is waiting for an object lock that holds by first thread, this situation is known as Deadlock. 12/27/2018 Java thread Applications

32 Java thread Applications
Example 12/27/2018 Java thread Applications

33 Java thread Applications
Exercise 1. Write a program using Simple threaded application 2. Write a program to create two threads where one prints even numbers & the other prints odd numbers 3. Write a program to print “welcome” using runnable interface 4. Create 2 threads & set the priority for the threads . 12/27/2018 Java thread Applications


Download ppt "Java Based Techhnology"

Similar presentations


Ads by Google