Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

How to create thread

1. Using the Thread class:

• Thread class provides constructors and methods to create


and perform operations on a thread.
• Thread class extends the 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 the method in which you write the code as to what you want
the thread to do
• public void start(): starts the execution of the thread. The programmer has
to explicitly call this method. JVM calls the run() method automatically.
• public void sleep(long milliseconds): Causes the currently executing thread to
sleep (temporarily stopping its execution) for the specified number of
milliseconds.
• public void join(): waits for the thread to complete its execution.
• public void join(long milliseconds): waits for a thread for the specified
milliseconds.
• 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 the currently executing
thread.
1) Java Thread Example by extending Thread
class
class CustomThread extends Thread {
public void run() {
System.out.println("CustomThread is running...");
}
public static void main(String args[]) {
Thread t1=new CustomThread();
t1.start();
}
}
Output:
CustomThread is running...
2) Java Thread Example by implementing
Runnable interface
class CustomThread implements Runnable{
public void run(){
System.out.println("thread is running…");
}

public static void main(String args[]) {


CustomThread ct = new CustomThread();
Thread t1 = new Thread(ct);
t1.start();
}
}

Output:
thread is running...
Differences Thread Runnable
Basic Thread is a class, used to create Runnable is an interface used to create a
a thread thread

Methods It has multiple methods including It has only one abstract method void
start() and run() run()

Memory More memory required Less memory required

Limitation Multiple Inheritance is not allowed If a class is implementing the runnable


in Java hence after a class extends interface then your class can extend
Thread class, it cannot extend any another class.
other class
3 constants defined 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.
How to Control the main thread of your application:
Class ThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread(); // get the current main thread
System.out.println(“Current Thread: “ + t); // print its details
t.setName(“My Custom Thread”); // change its name
System.out.println(“After name change:“ + t); // print details after changing its name
try {
for (int i = 0; i < 5; i++) {
System.out.println(i);
Thread.sleep(1000); // suspend the thread from executing for a second
}
} catch (InterruptedException e) { // some other thread wants to interrupt the sleeping thread
System.out.println(“Main thread is interrupted”);
}
}
}
Current Thread: Thread[main,5,main]
After name change:Thread[My Custom Thread,5,main]
0
1
2
3
4

Process finished with exit code 0


class NewThread implements Runnable {
Thread t;

NewThread() {
t = new Thread(this, "demoThread");
System.out.println("Child Thread: " + t);
}
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread:" + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child thread is interrupted");
}
System.out.println("Exiting Child Thread");
public class Main {
public static void main(String args[]) {
NewThread nt = new NewThread();
nt.t.start();

try {
for (int i = 0; i < 5; i++) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread is interrupted");
}
System.out.println("Exiting Main Thread");
}
}
Child Thread: Thread[demoThread,5,main]
Main Thread: 0
Child Thread:0
Child Thread:1
Main Thread: 1
Child Thread:2
Child Thread:3
Main Thread: 2
Child Thread:4
Exiting Child Thread
Main Thread: 3
Main Thread: 4
Exiting Main Thread

Process finished with exit code 0


class MultithreadingDemo extends Thread {
public void run() {
try {
System.out.println("Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
Sample output (yours may be different)

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Lab Activity/Exercise 23
Develop a Java program to create a class
MyThread. In this MyThread class, create a
constructor, call the base class constructor,
using super, and start the thread. The run
method of the class starts after this. It can be
observed that both the main thread and the
created child thread are executed
concurrently.
Lab Activity/Exercise 24
Write a Java program to create two threads, using
the runnable class. The start method will start each
of these newly created threads. Inside the run
method of each of these threads, there is a sleep()
for suspending each thread for 500 milliseconds).
public class ThreadJoinExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "t1");
Thread t2 = new Thread(new MyRunnable(), "t2");
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads are dead, exiting main thread");
Sample output

Thread started:::t1
Thread ended:::t1
Thread started:::t2
Thread ended:::t2
All threads are dead, exiting main thread
Synchronized Method
class PrintEvenOrOdd {
public synchronized void print(boolean printEven) { // behaves differently based on this flag

if (printEven) {
for (int i = 0; i < 10; i++) {
System.out.println(i * 2);
}
} else {
for (int i = 0; i < 10; i++) {
System.out.println(i * 2 + 1);
}
}
}
}
class Thread1 extends Thread { // First Thread – Even Thread
PrintEvenOrOdd pEO;

Thread1(PrintEvenOrOdd pEO) {
this.pEO = pEO;
}

public void run() {


pEO.print(true);
}
}

class Thread2 extends Thread { // Second Thread – Odd Thread


PrintEvenOrOdd pEO;

Thread2(PrintEvenOrOdd pEO) {
this.pEO = pEO;
}

public void run() {


pEO.print(false);
}
}
public class Main { // This is the test class
public static void main(String args[]) {
PrintEvenOrOdd obj = new PrintEvenOrOdd();

Thread1 t1 = new Thread1(obj);


Thread2 t2 = new Thread2(obj);

t1.start();
t2.start();
}
}
1
3
5
7
9
11
13
15
17
19
0
2
4
6
8
10
12
14
16
18

Process finished with exit code 0


Syncrhonized Block Example
public class Table {
void printTable(int x) {
synchronized(this) { // Synchronized block

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


System.out.println(x * i);
try {
Thread.sleep(400);
}
catch(InterruptedException ie) {
System.out.println(ie);
}
}
}
}
}
Syncrhonized Block Example…
public class Thread1 extends Thread {
Table t;

Thread1(Table t) {
this.t = t;
}

public void run() {


t.printTable(2);
}
}

public class Thread2 extends Thread {


Table t;

Thread2(Table t) {
this.t = t;
}

public void run() {


t.printTable(10);
}
}
Syncrhonized Block Example…
public class SynchronizedBlock {
public static void main(String[] args) {
Table t = new Table();
Thread1 t1 = new Thread1(t);
Thread2 t2 = new Thread2(t);
t1.start();
t2.start();
}
}
Output Sample…
Output:
2
4
6
8
10
12
14
16
18
20

10
20
30
40
50
60
70
80
90
100

You might also like