0% found this document useful (0 votes)
9 views21 pages

Experiment 7

Uploaded by

KS Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views21 pages

Experiment 7

Uploaded by

KS Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Experiment No.2.

Write a Java multi-threaded program to implement


the tortoise and hare story. Make the hare sleep at the
mid of the way and let the tortoise win.
Thread & Synchronization
Introduction
• Each part of such a program is called a thread, and each thread defines
a separate path of execution
• A multithreaded program contains two or more parts that can run
concurrently.
• Thus, multithreading is a specialized form of multitasking.

Advantages of Java Multithreading


• 1) It doesn't block the user because threads are independent and you
can perform multiple operations at same time.
• 2) You can perform many operations together so it saves time.
• 3) Threads are independent so it doesn't affect other threads if
exception occur in a single thread.
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.
What is Thread in java
• A thread is a lightweight sub process, a smallest unit of processing. It is
a separate path of execution.
• Threads are independent, if there occurs exception in one thread, it
doesn't affect other threads. It shares a common memory area.
• As shown 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 (Thread States)
• The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
Life cycle of a Thread (Thread States)
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.
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:
• By extending Thread class
• 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:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the 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().
• 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.
Java Thread Example by extending Thread
class
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();
}
}
Java Thread Example by implementing Runnable
interface
• class Multi3 implements Runnable
• {
• public void run()
• {
• System.out.println("thread is running...");
• }
• public static void main(String args[])
• {
• Multi3 m1=new Multi3();
• Thread t1 =new Thread(m1);
• t1.start();
• } }
Sleep method in java

• The sleep() method of Thread class is used to sleep a thread


for the specified amount of time.

Syntax of sleep() method in java


• The Thread class provides two methods for sleeping a
thread:
• public static void sleep(long miliseconds)throws
InterruptedException
• public static void sleep(long miliseconds, int nanos)throws
InterruptedException
Example of sleep method in java
• class TestSleepMethod1 extends Thread{
• public void run(){
• for(int i=1;i<5;i++){
• try{Thread.sleep(500);}
• catch(InterruptedException e){System.out.println(e);}
• System.out.println(i);
• }
• }
• public static void main(String args[]){
• TestSleepMethod1 t1=new TestSleepMethod1();
• TestSleepMethod1 t2=new TestSleepMethod1();
• t1.start();
• t2.start();
• }
• }
Can we start a thread twice
• No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run
once but for second time, it will throw exception.
Let's understand it by the example given below:
• public class TestThreadTwice1 extends Thread{
• public void run(){
• System.out.println("running...");
• }
• public static void main(String args[]){
• TestThreadTwice1 t1=new TestThreadTwice1();
• t1.start();
• t1.start();
• } }
• O/P:
• running
• Exception in thread "main" java.lang.IllegalThreadStateException
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
Ex:
• class TestJoinMethod1 extends Thread{ • O/P:
• public void run(){ • 1
• for(int i=1;i<=5;i++){ • 2
• 3
• try{
• 4
• Thread.sleep(500); • 5
• }catch(Exception e){System.out.println(e);} • 1
• System.out.println(i); • 1
• 2
• } }
• 2
• public static void main(String args[]){
• 3
• TestJoinMethod1 t1=new TestJoinMethod1(); • 3
• TestJoinMethod1 t2=new TestJoinMethod1(); • 4
• TestJoinMethod1 t3=new TestJoinMethod1(); • 4
• 5
• t1.start();
• 5
• try{
• t1.join();
• }catch(Exception e){System.out.println(e);}
• t2.start();
• t3.start();
• } }
getName(),setName(String) and getId() method:

• public String getName()


• public void setName(String name)
• public long getId()
Ex:
• class TestJoinMethod3 extends Thread{
• public void run(){
• System.out.println("running...");
• }
• O/P:
• public static void main(String args[]){ • Name of
• TestJoinMethod3 t1=new TestJoinMethod3();
t1:Thread-0
• TestJoinMethod3 t2=new TestJoinMethod3();
• System.out.println("Name of t1:"+t1.getName( • Name of
));
t2:Thread-1
• System.out.println("Name of t2:"+t2.getName(
)); • id of t1:8
• System.out.println("id of t1:"+t1.getId());
• t1.start(); • After changling
• t2.start(); name of t1:My
• t1.setName(“My Thread"); Thread
• System.out.println("After changing name of t1:
"+t1.getName());
• }
• }
Priority of a Thread (Thread Priority):

• Each thread have a priority. Priorities are represented by a number


between 1 and 10. In most cases, thread schedular schedules the
threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
• Three constants defiend in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY

• Default priority of a thread is 5 (NORM_PRIORITY). The value of


MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Ex:

• class TestMultiPriority1 extends Thread{


• public void run(){
• System.out.println("running thread name is:"+Thr • Output:
ead.currentThread().getName());
• System.out.println("running thread priority is:"+Th • running thread name
read.currentThread().getPriority());

is:Thread-0 running
• } thread priority is:10
• public static void main(String args[]){ running thread name
• TestMultiPriority1 m1=new TestMultiPriority1(); is:Thread-1 running
• TestMultiPriority1 m2=new TestMultiPriority1();
thread priority is:1
• m1.setPriority(Thread.MIN_PRIORITY);
• m2.setPriority(Thread.MAX_PRIORITY);
• m1.start();
• m2.start();
• } }

You might also like