Multi Threading Notes
Multi Threading Notes
Multithreading
3 4
Java Threads Creating thread in Java
A thread is a program unit that is executed 1. Define a class which you want to run as a
independently of other parts of the program. separate thread and implement the
Runnable interface. This interface has a
Java virtual machine executes each thread single method called run.
for a short amount of time and then switches
public interface Runnable{
to another thread. You can visualize the
void run();
thread as programs executing in parallel to
}
each other.
2. Place the code for the task into the run
method of the class.
5 6
7 8
Cont. Terminating Thread
public class mythread { A thread terminates when the run method returns.
public static void main(String [] args){ This is normal way of terminating a thread.
Runnable r1 = new greet("Hello");
Runnable r2 = new greet("bye");
If there is need to abruptly terminate a thread during
Thread t1 = new Thread(r1); execution, a thread must be interrupted.
Thread t2 = new Thread(r2); To notify a thread that it should clean up and terminate,
use the interrupt method
threadobject.interrupt();
t1.start();
t2.start();
This call does not terminate the thread; it merely sets a
}
flag in the thread data structure.
}
9 10
11 12
Race Conditions
A race condition occurs if the effect of
multiple threads on shared data depends on
the order in which the threads are scheduled.
All threads will compete to get hold of shared
resources.
13