100 likes | 111 Views
Learn the concept of multithreading in Java, its benefits, and methods of implementation. Includes a demo of matrix multiplication using multiple threads.
E N D
PRACTICAL#07 OBJECTIVE: TO UNDERSTAND MULTITHREADING
THREAD • Simply put, a thread is a program's path of execution. Most programs that run as a single thread, cause problems when multiple events or actions need to occur at the same time. • When multiple threads execute byte-code instruction sequences in the same program, that action is known as multithreading. • JVM has to keep track of each thread’s execution.
Let's say, for example, a program is not capable of drawing pictures while reading keystrokes. The program must give its full attention to the keyboard input lacking the ability to handle more than one event at a time. The ideal solution to this problem is the seamless execution of two or more sections of a program at the same time. Threads allows us to do this.
Benefits • Multithreaded GUI: More responsive • Faster execution • Helpful for networked environment to reduce idle time.
Threads in java There are two ways of creating threads: • Java accomplishes multithreading through its java.lang.Thread class. Each Thread object describes a single thread of execution. You should extend the Thread class and override the run method. • The second method is to implement the Runnable interface and write code for run method.
Implementing Runnable • The easiest way to create a thread is to create a class that implements the Runnableinterface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( )
Matrix Multiplication Code • Execute it and print the time at start and at the end.
Task • Write the same code for matrix multiplication and divide the code into ten threads. Also note the timestamp at the start and end of the program. Give your conclusion.