0% found this document useful (0 votes)
23 views11 pages

Multi Thread in

Uploaded by

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

Multi Thread in

Uploaded by

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

Java Thread class

Java provides Thread class to achieve thread programming.

Thread class provides constructors and methods to create and perform


operations on a thread.

Thread class extends Object class and implements Runnable interface.

Java Thread Methods

S.N Modifier Method Description


. and Type

1) void start() It is used to start the execution of the


thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified


amount of time.

4) static currentThread() It returns a reference to the currently


Thread executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread


object to pause and allow other threads
to execute temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended


thread.
15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group


and all of its subgroups.

17) boolean isDaemon() It tests if the thread is a daemon


thread.

18) void setDaemon() It marks the thread as daemon or user


thread.

19) void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has been


interrupted.

21) static interrupted() It tests whether the current thread has


boolean been interrupted.

22) static int activeCount() It returns the number of active threads


in the current thread's thread group.

23) void checkAccess() It determines if the currently running


thread has permission to modify the
thread.

24) static holdLock() It returns true if and only if the current


boolean thread holds the monitor lock on the
specified object.

25) static void dumpStack() It is used to print a stack trace of the


current thread to the standard error
stream.

26) StackTrace getStackTrace() It returns an array of stack trace


Element[] elements representing the stack dump
of the thread.

27) static int enumerate() It is used to copy every active thread's


thread group and its subgroup into the
specified array.

28) Thread.Stat getState() It is used to return the state of the


e thread.

29) ThreadGrou getThreadGroup It is used to return the thread group to


p () which this thread belongs

30) String toString() It is used to return a string


representation of this thread, including
the thread's name, priority, and thread
group.

31) void notify() It is used to give the notification for


only one thread which is waiting for a
particular object.

32) void notifyAll() It is used to give the notification to all


waiting threads of a particular object.

33) void setContextClass It sets the context ClassLoader for the


Loader() Thread.

34) ClassLoader getContextClass It returns the context ClassLoader for


Loader() the thread.

35) static getDefaultUnca It returns the default handler invoked


Thread.Unc ughtExceptionH when a thread abruptly terminates due
aughtExcep andler() to an uncaught exception.
tionHandler

36) static void setDefaultUncau It sets the default handler invoked


ghtExceptionHa when a thread abruptly terminates due
ndler() to an uncaught exception.

simple multithreading Java program that demonstrates how threads work in Java:

public class ThreadDemo {

public static void main(String[] args) {

// create two threads

Thread t1 = new MyThread("Thread 1");

Thread t2 = new MyThread("Thread 2");

// start the threads

t1.start();

t2.start();

class MyThread extends Thread {


private String name;

public MyThread(String name) {

this.name = name;

public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(name + ": " + i);

try {

// sleep for a random amount of time

Thread.sleep((int) (Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

In this program, we create a ThreadDemo class and a MyThread class that


extends the Thread class. We then create two instances of the MyThread
class, passing in different names for each thread.

We then start the threads by calling their start() methods. This causes
the run() method of each thread to be executed in a separate thread of
execution.

In the run() method of the MyThread class, we loop from 1 to 5 and print
out the thread name and the current value of i. We then sleep for a
random amount of time using the Thread.sleep() method to simulate
some work being done by the thread.

When you run the program, you should see output like this:

Thread 1: 1

Thread 2: 1
Thread 1: 2

Thread 2: 2

Thread 1: 3

Thread 2: 3

Thread 1: 4

Thread 2: 4

Thread 2: 5

Thread 1: 5

As you can see, the two threads are executing concurrently, interleaving their
output in an unpredictable way. This demonstrates how multithreading can be
used to perform multiple tasks simultaneously.

Java program that creates a thread which will display prime numbers after every
5 seconds:
public class PrimeNumberThread extends Thread {
public void run() {
int num = 2;
while (true) {
if (isPrime(num)) {
System.out.println(num);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num++;
}
}

private boolean isPrime(int n) {


if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] args) {


PrimeNumberThread thread = new PrimeNumberThread();
thread.start();
}
}

Java program that creates two threads, Thread1 and Thread2, and sets the
maximum priority to Thread2 and the minimum priority to Thread1:

public class PriorityThreadDemo {


public static void main(String[] args) {
Thread thread1 = new Thread(new Thread1());
Thread thread2 = new Thread(new Thread2());

thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);

thread1.start();
thread2.start();
}
}

class Thread1 implements Runnable {


public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Thread2 implements Runnable {


public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

What is thread?
threads are a powerful tool in Java programming that allow for parallel execution
of code, enabling better performance and increased responsiveness in complex
applications.

In Java, a thread is a separate path of execution that runs concurrently


with other threads. Each thread represents a separate flow of control
within a program, and allows multiple operations to be performed
simultaneously.

Java provides built-in support for multithreading, which allows a program


to perform multiple tasks simultaneously. By using multiple threads, a
program can become more responsive to user input, can take advantage
of modern multicore processors, and can make more efficient use of
system resources.

A Java program can create multiple threads by extending the Thread class
or by implementing the Runnable interface. When a thread is created, it is
given a priority, which determines the order in which it is scheduled to run
by the Java Virtual Machine (JVM).

Java threads can be either daemon threads or non-daemon threads.


Daemon threads are low-priority threads that run in the background and
are used to perform tasks such as garbage collection. Non-daemon
threads are high-priority threads that are used for user-visible tasks such
as user interface updates or network communications.

Java provides a number of methods for managing threads, such as


start(), join(), and sleep(). The start() method is used to start a thread,
while the join() method is used to wait for a thread to complete. The
sleep() method is used to pause a thread for a specified amount of time.

Define setpriority () method in java multithreading.

The setPriority() method is a method in Java multithreading that is used


to set the priority of a thread. The Thread class in Java provides the
setPriority() method, which allows a program to specify the relative
priority of a thread compared to other threads.

The setPriority() method takes a single parameter, which is an integer


that represents the priority of the thread. The integer value can range
from 1 (lowest priority) to 10 (highest priority), with 5 being the default
priority.

In Java, threads are scheduled for execution by the JVM based on their
priority. Higher priority threads are given preference over lower priority
threads. By default, all threads are assigned the priority of the thread that
created them.

It's important to note that setting a thread's priority is only a suggestion


to the JVM, and the JVM may not always honor the priority setting due to
platform-specific behavior or other factors.

Here is an example of using the setPriority() method to set the priority


of a thread:

public class ThreadPriorityDemo {

public static void main(String[] args) {

Thread thread1 = new Thread(new MyRunnable());


Thread thread2 = new Thread(new MyRunnable());

// Set the priority of thread1 to the maximum value

thread1.setPriority(Thread.MAX_PRIORITY);

// Set the priority of thread2 to the minimum value

thread2.setPriority(Thread.MIN_PRIORITY);

// Start both threads

thread1.start();

thread2.start();

class MyRunnable implements Runnable {

public void run() {

// Code to be executed by the thread

In the above example, we create two threads using the Thread class and set
their priorities using the setPriority() method. The Thread.MAX_PRIORITY
constant is used to set the priority of thread1 to the maximum value, while the
Thread.MIN_PRIORITY constant is used to set the priority of thread2 to the
minimum value. Finally, we start both threads using the start() method.
Thread Life Cycle:

In Java, a thread goes through several states in its life cycle. These states
are defined by the Thread.State enum, and they are as follows:

1. NEW: A thread is in the NEW state when it has been created but has not yet
started running.
2. RUNNABLE: A thread is in the RUNNABLE state when it has been started and is
either running or waiting to be scheduled to run by the operating system.
3. BLOCKED: A thread is in the BLOCKED state when it is waiting for a monitor
lock to be released so that it can enter a synchronized block or method.
4. WAITING: A thread is in the WAITING state when it is waiting for a specific
condition to be met before it can continue running. For example, a thread
might wait for another thread to complete its work before it can continue.
5. TIMED_WAITING: A thread is in the TIMED_WAITING state when it is waiting for
a specific period of time before it can continue running. For example, a
thread might sleep for a specified amount of time before continuing.
6. TERMINATED: A thread is in the TERMINATED state when it has completed its
work and has either been terminated or has naturally terminated.

The following is a basic outline of the life cycle of a thread in Java:

1. NEW: A thread is created using the new keyword and is in the NEW state.
2. RUNNABLE: The start() method is called on the thread, and it becomes
eligible for scheduling by the operating system. It transitions to the
RUNNABLE state.
3. RUNNING: The operating system schedules the thread to run, and it
transitions to the RUNNING state.
4. BLOCKED or WAITING or TIMED_WAITING: While running, a thread may
transition to one of these states depending on the conditions it
encounters. For example, if it enters a synchronized block or method, it
may become BLOCKED. If it calls the wait() method, it becomes WAITING,
and if it calls the sleep() method, it becomes TIMED_WAITING.
5. RUNNABLE: When the blocking condition is resolved or the specified wait
time elapses, the thread becomes eligible for scheduling again and
transitions back to the RUNNABLE state.
6. TERMINATED: The thread completes its work and either terminates naturally
or is terminated explicitly using the stop() method. It transitions to the
TERMINATED state.

It's worth noting that threads can transition between states multiple times
during their life cycle, depending on the conditions they encounter while
running.

You might also like