0% found this document useful (0 votes)
53 views

Multithreading Class Notes Java

The document discusses threads and concurrency in Java. It explains how to create threads by extending the Thread class and implementing the Runnable interface. It also covers thread life cycle and states, synchronized methods and blocks for controlling access to shared resources, and examples of creating and running multiple threads.

Uploaded by

daniel007work
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Multithreading Class Notes Java

The document discusses threads and concurrency in Java. It explains how to create threads by extending the Thread class and implementing the Runnable interface. It also covers thread life cycle and states, synchronized methods and blocks for controlling access to shared resources, and examples of creating and running multiple threads.

Uploaded by

daniel007work
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

The thread

scheduler
always chooses
the thread for
execution only if
it is already in
the RUNNABLE
state.
How to create a thread in Java

• There are two ways for creating a thread in Java:

– by extending the Thread class;

– By implementing the Runnable interface.

– Both are in the java.lang package


The Thread Class and the Runnable
Interface
• The Thread class defines several methods
that help manage threads.
Using isAlive( ) and join( )
• Their general form
final boolean isAlive( )
final void join( ) throws InterruptedException
The Main Thread
• main thread is important for two reasons:
• It is the thread from which other “child”
threads will be spawned.
• It must be the last thread to finish execution
because it performs various shutdown actions.
• When a Java program starts up, one thread
begins running immediately. This is usually
called the main thread.
• When we extend Thread class,
• each thread creates unique objects of thread class.
• For example, if you create 5 threads, we have 5
different objects in the memory.

• When we implement Runnable interface,


• then we create only one object the thread class.
• And the same object we pass to multiple threads.
• Meaning, all threads share the same object of the thread
class.
//My task the tread class
/My task is the tread class
class Task extends Thread {
class Task implements Runnable {
public void run() {
public void run() {
System.out.println("\nThread is
System.out.println("\nTread
running the task\n");
is running the task\n"); }
}
}
}
public class Sample {
public class Sample {
public static void main(String[] args){
public static void main(String[] args)
// Create one object of Task Thread class
{
Task r = new Task();
Task t1 = new Task();
Thread t1 = new Thread(r);
t1.start();
t1.start();
Task t2 = new Task();
Thread t2 = new Thread(r);
t2.start();
t2.start(); }
}
}
}
class MyThread1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1 - Count: " + i); } } }
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable Thread - Count: " + i); } } }
public class Exam {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1(); // Using extends Thread
t1.start(); // Start the thread
MyRunnable ob = new MyRunnable(); // Using implements Runnable
Thread t2 = new Thread(ob);
t2.start(); // Start the thread
// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread - Count: " + i); } } }
The Java Thread Model
• Single threaded system uses event loop with
polling.
• polling mechanism is eliminated by using
multithreading.
• One thread can pause without stopping other
parts of your program.
• Thread states are running, read to run, suspend,
resume, blocked, and terminated.
Methods defined by Thread

static void sleep(long milliseconds) throws InterruptedException

static void sleep(long milliseconds, int nanoseconds) throws


InterruptedException
• After you create a class that implements Runnable, you will
instantiate an object of type Thread from within that class.
• Thread defines several constructors.
Thread(Runnable threadOb, String threadName)
– threadOb is an instance of a class that implements the
Runnable interface. This defines where execution of the
thread will begin. The name of the new thread is specified
by threadName.
• After the new thread is created, it will not start running until
you call its start( ) method, which is declared within Thread.
void start( )
• super( ) inside NewThread invokes the following
form of the Thread constructor:
public Thread(String threadName)
Here, threadName specifies the name of the thread.

• The Thread class defines several methods that can


be overridden by a derived class.
No. Key Thread Runnable

1 Basic Thread is a class. It is used to Runnable is a functional interface


create a thread which is used to create a thread

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

3 Each thread creates a unique Multiple threads share the same


object and gets associated with it objects.

4 Memory More memory required Less memory required

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


in java hence after a class extends runnable interface then your class can
Thread class, it can not extend any extend another class.
other class
Creating Multiple Threads
class NewThread implements Runnable {

String name; // name of thread

Thread t;

NewThread(String threadname) {

name = threadname;

t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start(); // Start the thread }


// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2

output Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
Synchronization
• When two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used
by only one thread at a time. The process by which this is
achieved is called synchronization.
• Key to synchronization is Monitor also called as semaphore
• A monitor is an object that is used as a mutually exclusive
lock, or mutex. Only one thread can own a monitor at a given
time.
• The program without synchronization is
package com.mycompany.example;
class Table{
void print(int val){
for(int i=1;i<=10;i++){
System.out.println(val*i);
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println(e);
}
}
}
}
class Thread1 extends Thread{ class Thread2 extends Thread{
Table t; Table t;
Thread1(Table t){ Thread2(Table t){
this.t=t; this.t=t;
} }
public void run(){ public void run(){
t.print(4); t.print(6);
} }
} }
public class Example

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:
6
4
24
8
42
12
28
12
48
18
32
24
54
16
36
30
60
20
40
36
class Table{
synchronized void print(int 4 6
val){ 8 12
for(int i=1;i<=10;i++){ 12 18
System.out.println(val*i); 16 24
20 30
try{
24 36
Thread.sleep(1000); 28 42
}catch(Exception e){ 32 48
System.out.println(e); 36 54
40 60
}
}
}
}
The synchronized Statement
• While creating synchronized methods within classes
that you create is an easy and effective means of
achieving synchronization, it will not work in all cases.
• To understand why, consider the following.
• Imagine that you want to synchronize access to objects
of a class that was not designed for multithreaded
access. That is, the class does not use synchronized
methods.
• Further, this class was not created by you, but by a third
party, and you do not have access to the source code.
Thus, you can’t add synchronized to the appropriate
methods within the class.
simply put calls to the methods defined by this
class inside a synchronized block.

//The synchronized Statement Second METHOD


// to make it synchronize

synchronized(object) {
// statements to be synchronized
}
public class Example
{
public static void main(String[] args) {
Table t=new Table();
Thread1 t1=new Thread1(t);
Thread2 t2=new Thread2(t);
t1.start();
t2.start();
}
}
Synchronized block

class Thread2 extends Thread{


class Thread1 extends Thread{
Table t;
Table t;
Thread2(Table t){
Thread1(Table t){
this.t=t;
this.t=t;
}
}
public void run(){
public void run(){
synchronized (t) {
synchronized (t) {
t.print(6);
t.print(4); }
}
}
}
}
}

You might also like