Multithreading in Java - Newww
Multithreading in Java - Newww
3] But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exceptions occur in a single
thread.
Multitasking
Each process has its own address in memory i.e. each process allocates separate memory
area.
Process is heavyweight.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
1
2] Thread-based Multitasking (Multithreading)
Thread is lightweight.
Eg:
In MS-Word (i.e Process) there is auto spelling checking, line count, auto-saving etc are threads
running in one process.
Thread in java
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.
2
Figure shows, 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.
But for better understanding the threads, we are explaining it in the 5 states.
1] Newborn state
2] Runnable state
3] Running state
start stop
Blocked state
Idle thread
Idle thread
Fig: State transition diagram of a thread
3
1) Newborn state
When we create a thread object, the thread is born and is said to be in newborn state. The thread
is not yet scheduled for running. At this state, we can do only one of the following things with it:
Newborn
state
start stop
2) Runnable
It means that the thread is ready for execution and is waiting for the availability of the processor.
That is the thread has joined the queue of threads that are waiting for execution. If all the threads
have equals priority, then they are given time slots for execution in round robin fashion i.e first
come first serve manner. The thread that relinquishes control and join the queue at the end and
again waits for its turn. This process of assigning time to threads is known as time-slicing.
However, if we want a thread to relinquish control to another thread to equal priority before its
turn comes, we can do so by using the yield() method.
yield()
.
……. ……. ……..
. . . .
Running Runnable Thread’s
Thread
4
3) Running
Running means that the processor has given its time to the thread for its execution. The thread
runs until it relinquishes control on its own. A running thread may relinquish its control in one of
the following situation:
i. It has been suspended using suspend() method. A suspended thread can be revived by
using the resume() method. This approach is useful when we want to suspend a thread for
some time due to certain reason, but do not want to kill it.
suspended()
. .
Resume()
.
Running Runnable Suspended
ii. It has been made to sleep. We can put a thread to sleep for a specified time period using
the method sleep(time) where time is in milliseconds. This means that the thread is out
queue during this time period. The thread re-enters the runnable state as soon as this time
period is finished.
sleep(t)
after(t)
. . .
Running Runnable Suspended
5
iii. It has been told to wait until some event occurs. This is done using the wait() method.
The thread can be scheduled to run again using the notify() method.
wait()
notify()
. . .
Running Runnable Waiting
4) Blocked
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping or waiting
in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not
dead and therefore fully qualified to run again.
A running thread ends its life when it has completed executing its run() method. It is a natural
death. However we can kill it by sending stop message using stop() method to it at any state thus
causing a premature death. A thread can be killed as soon as it born or while it is running or even
when it is in blocked state.
6
How to create thread
Creating threads in java is simple. Threads are implemented in the form of Objects that contain a method
called “run()” method. The run() method is the heart and soul of any thread. It makes up the entire body
of a thread in which thr thread’s behavior can be implemented. A run() method would appear as follows:
Syntax:
The run() method should be invoked by an object of the concerned thread. This can be achieved by
creating the thread and initiating it with the help of another thread method called “start()” method.
Example:
System.out.println(i);
}
}
7
{
DemoThread d1=new DemoThread();
DemoThread d2=new DemoThread();
d1.start();
d2.start();
}
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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
8
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.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
When the thread gets a chance to execute, its target run() method will run.
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
} }
t1.start(); t2.start(); } }
9
Note: As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time,the thread shedular picks up another thread and so on.
Example
System.out.println("running...");
t1.start();
t1.start();
Output: running
Invoking the run() method from main thread, the run() method goes onto the current call stack
rather than at the beginning of a new call stack.
System.out.println("running...");
10
t1.run();//fine, but does not start a separate call stack
} }
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
t1.run();
t2.run();
11
}
Output:1
As you can see in the above program that there is no context-switching because here t1 and t2 will be
treated as normal object not thread object.
12
13
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:
Example of join()
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
14
In the above example, when t1 completes its task then t2 and t3 starts executing.
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
In the above example, when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts
executing.
15
getName(),setName(String) and getId() method:
class demo extends Thread{
System.out.println("running...");
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Pradeep");
} }
16
The currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.
Example
System.out.println(Thread.currentThread().getName());
t1.start();
t2.start();
17