Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
INFORMATION SCIENCE 7TH SEM 10IS753 –JAVA &J2EE Author Details: Name: Praveena.M Designation:AP Department: ISE ISE MVJCE 2014 UNIT-3 Multithreading in Java Multithreading is a process of executing multiple threads simultaneously. Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes. Multithreading is mostly used in games, animation etc. Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: Process-based Multitasking(Multiprocessing) Thread-based Multitasking(Multithreading) 1)Process-based Multitasking (Multiprocessing) Each process have its own address in memory i.e. each process allocates separate memory area. Process is heavyweight. Cost of communication between the process is high. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. 2)Thread-based Multitasking (Multithreading) Threads share the same address space. Thread is lightweight. Cost of communication between the thread is low. Note:At least one process is required for each thread. What is Thread? A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process. 2 ISE MVJCE 2014 In the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. Life cycle of a Thread A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows: 1. New 2. Runnable 3. Running 3 ISE MVJCE 2014 4. Non-Runnable (Blocked) 5. Terminated 1)New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2)Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 3)Running The thread is in running state if the thread scheduler has selected it. 4)Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 4 ISE MVJCE 2014 5)Terminated A thread is in terminated or dead state when its run() method exits. How to create thread: There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. Thread class: Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface. Commonly used Constructors of Thread class: Thread() Thread(String name) Thread(Runnable r) Thread(Runnable r,String name) Commonly used methods of Thread class: 1. public void run(): is used to perform action for a thread. 2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. 3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 4. public void join(): waits for a thread to die. 5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 6. public int getPriority(): returns the priority of the thread. 7. public int setPriority(int priority): changes the priority of the thread. 8. public String getName(): returns the name of the thread. 9. public void setName(String name): changes the name of the thread. 10. public Thread currentThread(): returns the reference of currently executing thread. 11. public int getId(): returns the id of the thread. 12. public Thread.State getState(): returns the state of the thread. 13. public boolean isAlive(): tests if the thread is alive. 14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 15. public void suspend(): is used to suspend the thread(depricated). 16. public void resume(): is used to resume the suspended thread(depricated). 17. public void stop(): is used to stop the thread(depricated). 18. public boolean isDaemon(): tests if the thread is a daemon thread. 19. public void setDaemon(boolean b): marks the thread as daemon or user thread. 20. public void interrupt(): interrupts the thread. 21. public boolean isInterrupted(): tests if the thread has been interrupted. 5 ISE MVJCE 2014 22. public static boolean interrupted(): tests if the current thread has been interrupted. Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). 1. public void run(): is used to perform action for a thread. Starting a thread: start() method of Thread class is used to start a newly created thread. It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run. 1)By extending Thread class: 1. 2. 3. 4. 5. 6. 7. 8. 9. class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } } Output:thread is running... Who makes your class object as thread object? Thread class constructor allocates a new thread object.When you create object of Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first statement).So your Multi class object is thread object now. 2)By implementing the Runnable interface: 1. class Multi3 implements Runnable{ 2. public void run(){ 3. System.out.println("thread is running..."); 4. } 5. 6. public static void main(String args[]){ 7. Multi3 m1=new Multi3(); 8. Thread t1 =new Thread(m1); 9. t1.start(); 10. } 6 ISE MVJCE 2014 11. } Output:thread is running... If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute. The join() method: The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Syntax: public void join()throws InterruptedException public void join(long milliseconds)throws InterruptedException 1. //<b><i>Example of join() method</i></b> 2. 3. class Multi extends Thread{ 4. public void run(){ 5. for(int i=1;i<=5;i++){ 6. try{ 7. Thread.sleep(500); 8. }catch(Exception e){System.out.println(e);} 9. System.out.println(i); 10. } 11. } 12. public static void main(String args[]){ 13. Multi t1=new Multi(); 14. Multi t2=new Multi(); 15. Multi t3=new Multi(); 16. t1.start(); 17. try{ 18. t1.join(); 19. }catch(Exception e){System.out.println(e);} 20. 21. t2.start(); 22. t3.start(); 23. } 24. } Output:1 2 3 4 5 1 1 7 ISE MVJCE 2014 2 2 3 3 4 4 5 5 Synchronization Synchronization is the capability of control the access of multiple threads to any shared resource. Synchronization is better in case we want only one thread can access the shared resource at a time. Why use Synchronization? The synchronization is mainly used to 1. To prevent thread interference. 2. To prevent consistency problem. Types of Synchronization There are two types of synchronization 1. Process Synchronization 2. Thread Synchronization Here, we will discuss only thread synchronization. Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication. Mutual Exclusive 1. Synchronized method. 2. Synchronized block. 3. static synchronization. Cooperation (Inter-thread communication) 8 ISE MVJCE 2014 Understanding the problem without Synchronization In this example, there is no synchronization, so output is inconsistent. Let's see the example: 1. Class Table{ 2. 3. void printTable(int n){//method not synchronized 4. for(int i=1;i<=5;i++){ 5. System.out.println(n*i); 6. try{ 7. Thread.sleep(400); 8. }catch(Exception e){System.out.println(e);} 9. } 10. 11. } 12. } 13. 14. class MyThread1 extends Thread{ 15. Table t; 16. MyThread1(Table t){ 17. this.t=t; 18. } 19. public void run(){ 20. t.printTable(5); 21. } 22. 23. } 24. class MyThread2 extends Thread{ 25. Table t; 26. MyThread2(Table t){ 27. this.t=t; 28. } 29. public void run(){ 30. t.printTable(100); 31. } 32. } 33. 34. class Use{ 35. public static void main(String args[]){ 36. Table obj = new Table();//only one object 37. MyThread1 t1=new MyThread1(obj); 38. MyThread2 t2=new MyThread2(obj); 39. t1.start(); 40. t2.start(); 41. } 42. } Output: 5 100 10 200 9 ISE MVJCE 2014 15 300 20 400 25 500 Solution by synchronized method If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the method returns. 1. //Program of synchronized method 2. Class Table{ 3. synchronized void printTable(int n){//synchronized method 4. for(int i=1;i<=5;i++){ 5. System.out.println(n*i); 6. try{ 7. Thread.sleep(400); 8. }catch(Exception e){System.out.println(e);} 9. } 10. 11. } 12. } 13. 14. class MyThread1 extends Thread{ 15. Table t; 16. MyThread1(Table t){ 17. this.t=t; 18. } 19. public void run(){ 20. t.printTable(5); 21. } 22. 23. } 24. class MyThread2 extends Thread{ 25. Table t; 26. MyThread2(Table t){ 27. this.t=t; 28. } 29. public void run(){ 30. t.printTable(100); 31. } 32. } 33. 34. class Use{ 35. public static void main(String args[]){ 36. Table obj = new Table();//only one object 37. MyThread1 t1=new MyThread1(obj); 10 ISE MVJCE 2014 38. MyThread2 t2=new MyThread2(obj); 39. t1.start(); 40. t2.start(); 41. } 42. } Output: 5 10 15 20 25 100 200 300 400 500 Event and Listener (Event Handling): Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling. Event classes and Listener interfaces: Event Classes Listener Interfaces ActionEvent ActionListener MouseEvent MouseListener and MouseMotionListener MouseWheelEvent MouseWheelListener KeyEvent KeyListener ItemEvent ItemListener TextEvent TextListener AdjustmentEvent AdjustmentListener WindowEvent WindowListener ComponentEvent ComponentListener ContainerEvent ContainerListener FocusEvent FocusListener Steps to perform EventHandling: Following steps are required to perform event handling : 1. Implement the Listener interface and overrides its methods 2. Register the component with the Listener 11 ISE MVJCE 2014 Example of event handling within class: 1. import java.awt.*; 2. import java.awt.event.*; 3. 4. class AEvent extends Frame implements ActionListener{ 5. TextField tf; 6. AEvent(){ 7. 8. tf=new TextField(); 9. tf.setBounds(60,50,170,20); 10. 11. Button b=new Button("click me"); 12. b.setBounds(100,120,80,30); 13. 14. b.addActionListener(this); 15. 16. add(b);add(tf); 17. 18. setSize(300,300); 19. setLayout(null); 20. setVisible(true); 21. 22. } 23. 24. public void actionPerformed(ActionEvent e){ 25. tf.setText("Welcome"); 26. } 27. 28. public static void main(String args[]){ 29. new AEvent(); 30. } 31. } 12 ISE MVJCE 2014 Example of event handling by Outer class: 1. import java.awt.*; 2. import java.awt.event.*; 3. 4. class AEvent2 extends Frame implements ActionListener{ 5. TextField tf; 6. AEvent2(){ 7. 8. tf=new TextField(); 9. tf.setBounds(60,50,170,20); 10. 11. Button b=new Button("click me"); 12. b.setBounds(100,120,80,30); 13. 14. b.addActionListener(this); 15. 16. add(b);add(tf); 17. 18. setSize(300,300); 19. setLayout(null); 20. setVisible(true); 21. 22. } 23. 24. public void actionPerformed(ActionEvent e){ 25. tf.setText("Welcome"); 26. } 27. 28. public static void main(String args[]){ 29. new AEvent2(); 13 ISE MVJCE 2014 30. } 31. } 1. import java.awt.event.*; 2. 3. class Outer implements ActionListener{ 4. AEvent2 obj; 5. Outer(AEvent2 obj){ 6. this.obj=obj; 7. } 8. 9. public void actionPerformed(ActionEvent e){ 10. obj.tf.setText("welcome"); 11. } 12. 13. } 14 ISE MVJCE 2014 15