0% found this document useful (0 votes)
10 views22 pages

05 Thread

The document provides an overview of Java threading, including concepts of threads, multithreading, and thread synchronization. It explains how to create and manage threads in Java, using both the Thread class and the Runnable interface, along with examples of thread programming. Additionally, it discusses thread states, methods, priorities, and synchronization techniques to control access to shared resources.

Uploaded by

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

05 Thread

The document provides an overview of Java threading, including concepts of threads, multithreading, and thread synchronization. It explains how to create and manage threads in Java, using both the Thread class and the Runnable interface, along with examples of thread programming. Additionally, it discusses thread states, methods, priorities, and synchronization techniques to control access to shared resources.

Uploaded by

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

JAVA TECHNOLOGY

JAVA THREADS

1
Content
❑ Concept
❑ Thread status

❑ Thread synchronization

2
Threading and multithreading
• Thread: the commands that the CPU must execute

• New operating systems allow multiple threads to execute


concurrently → Multiple applications running in parallel.
– A thread is a sequence of instructions in memory.

– One application corresponds to one process

– One process can have many threads OS


• Threads are managed by a queue mechanism

thread

Process
Threading and multithreading
Benefit of multithreading
• Increase CPU usage: Most of the execution time of an
application is waiting for the user to enter data, so CPU
usage is not effective.

• Create synchronization between objects.


For example, in a game there are many threads processing at the same time such as
images, sound and logic.

• Manage time in applications.


Thread in Java
• Main thread: is the thread that contains other threads. This is the
thread for the current Java Application.

• Child thread: is a thread created from another thread.

• When an application executes, the main thread is run, when it


encounters statements that create child threads, child threads are
created. When the main thread ends, the application ends.
Thread programming in java
• Method 1: Build a subclass of java.lang.Thread class, override the run()
method to suit the purpose of the problem.
public class Main extends Thread {
public void run() {
System.out.println("This code is running in athread");
} }

• Method 2: Build a class implementing the Runnable interface.


public class Main implements Runnable {
public void run() {
System.out.println("This code is running in athread");
} }
• Attention:
– No need to import java.lang because it is a basic package
– java.lang.Thread is a built-in Java class that implements the Runnable interface.
– The java.lang.Runnable interface has only one run() method.
Thread programming in java
package create_thread_demo;
public class Mythread extends Thread{
public void run() {
try {
System.out.println("Inside Mythread");
Thread.sleep(2000);
System.out.println("Finish Mythread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("Start");
Mythread t1 = new Mythread();
t1.start();
System.out.println("Finish");
}
}

Start Mythread
Finish Inside Mythread Finish Mythread
Inside Mythread
Finish Mythread main
Start Finish t
Thread programming in java
package create_thread_demo;
public class Mythread extends Thread{
public void run() {
try {
System.out.println("Inside Mythread");
Thread.sleep(2000);
System.out.println("Finish Mythread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws InterruptedException


{
Mythread t1 = new Mythread();
t1.start();
t1.join();
System.out.println("Finish");
}
Mythread
} Inside Mythread Finish Mythread

Inside Mythread main


Finish Mythread
Finish
Finish t1.join()
t
Thread programming in java
package create_thread_demo;

public class Mythread implements Runnable{


public void run() {
try {
System.out.println("Inside Mythread");
Thread.sleep(2000);
System.out.println("Finish Mythread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws InterruptedException {


Mythread mt1 = new Mythread();
Thread thread = new Thread(mt1);
thread.start();
Thread.join();
System.out.println("Finish");
}
}

Mythread
Inside Mythread Inside Mythread Finish Mythread

Finish Mythread main


Finish t1.join() Finish
t
Thread programming in java
• Write a program to calculate the sum of numbers from 1 - 1,000,000,000
and record the completion time
• Use multi-threading technique to speed up the calculation (10 threads)

public class Calculator{


public long sum() {
long sum = 0;
for ( int i = 0; i < 1000000000; i ++) {
sum += i ;
}
return sum ;
}

public static void main(String[] args ) {


Calculator cal = new Calculator();
long start = System.currentTimeMillis();
long sum = cal.sum();
long end = System.currentTimeMillis();
System.out.println ("sum: " + sum );
System.out.println ("Time is ms : " + ( end - start ));
}
}
Thread programming in java

Split into 10 threads Give list total


• Suggest :
0 0 1
sum
s1
sum s2



sum

1,000,000,000 1,000,000,000 s10 10


Thread status
Born
Time out new Thread()

Available sieve
(Ready)

notify() notify()

start()

In progress wait Sleep Bag temporary Bag lock


(Waiting) (Sleeping) postpone (Blocked)
(Suspended)
run()

wait() sleep() wait()

In progress run
(Running)

When wait the variable


try like export / import
stop() or run finished

Behavior to force state


transition
Already die
(Dead)
Thread status
• When a thread is created, it does not run immediately, but is in a
ready state. Only when the start() method is called will the thread
execute (run the code in the run() method).

• The executing thread can be paused by the sleep() method for a


period of time and will be ready again after the time expires. The
sleeping thread does not use CPU resources.

• When multiple threads are executed at the same time, if one thread
holds a resource and does not release it, it will cause other threads to
not be able to use this resource (resource starvation). To avoid this
situation, Java provides the Wait-Notify mechanism. The wait()
method helps put a thread into a waiting state.
Thread status

• When a thread is suspended or suspended, it enters the suspended


state. The wait() method is used for this purpose.

• When a suspended thread is resumed, its state is resumed. The


notify() method is used for this purpose.

• When a thread is waiting for an event such as data input/output. The


thread enters the blocked state.

• When a thread finishes executing the run() method or encounters the


stop() method, the thread is dead.
Methods of the thread

Methods Purpose of use


final String getName() Get thread name
final boolean isAlive() Check thread still live or not
Final void setName(String NewName) Rename the thread
final void join() throws
Wait for this thread to die
interruptedException

public final boolean isDaemon() Check if it is a daemon thread


static void sleep(long millisec) Delay the thread for a period of time
void start() Thread execution​
static int activeCount() Count active threads
Pause the current thread so that other
static void yield()
threads can continue executing
Two types of threads

• Daemon threads: system threads, running in the


background, are threads that provide services to other
threads. Processes in the JVM exist only when daemon
threads exist. The JVM has at least 1 daemon thread, the
“garbage collection” thread

• User-created threads
Example of thread methods
package create_thread_demo ; Thread count: 3
public class Mythread extends Thread{ Inside test thread 2
Inside test thread 1
public void run() {
Finish test thread 2
try { Finish test thread 1
System.out.println ("Inside " + this.getName()); Finish
Thread.sleep(2000);
System.out.println("Finish " + this.getName ());
} catch(InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args ) throws InterruptedException {
Mythread t1 = new Mythread ();
t1.setName("test thread 1");
t1.start();
Mythread t2 = new Mythread();
t2.setName("test thread 2");
t2.start();
System.out.println("Thread count: " + Thread.activeCount());
t1.join();
t2.join();
System.out.println("Finish");
}
}
Thread priority
• Threads share CPU time
– Threads at the end of the queue will take longer to be executed by the CPU.

– There is a need to change the priority of the thread.

– Java provides 3 constants that describe the priority of a thread (other priorities use
an integer from 1.. 10).

• NORM_PRIORITY: value 5

• MAX_PRIORITY: value 10

• MIN_PRIORITY: value 1

• The default priority of a thread is NORMAL_PRIORITY. Child threads


have the same priority as the parent thread (due to inheritance)
Thread priority

• final void setPriority(int newPriority)

• final int getPriority()

• The thread is not executed when


– Thread not having highest priority

– Thread sleep()

– Thread wait()

– Thread blocked because waiting for I/O


Synchronization between threads
• Synchronization between threads to control access to
shared resources: Only one thread can access a resource
at a time

• Methods of synchronization between threads:


– Method synchronization

– Block synchronization Thread 1

Thread 2 resources

Thread 3
Example
// Table.java
class Table {
void printTable(int n) {// method not synchronized
for (int i = 1; i <= 5; i++) {
System.out.println(n * i); 5
try {Thread.sleep(400);} 20
catch (Exception e) {System.out.println(e);} 40
}}} 10
60
// MyThread1.java 15
public class MyThread1 extends Thread { 20
Table t; 80
private int multiplier; 25
MyThread1(Table t, int multiplier) { 100
this.t = t;
this.multiplier = multiplier;
}
public void run() {
t.printTable(multiplier);
}
public static void main(String args[]) {
Table obj = new Table();// only one object
MyThread1 t1 = new MyThread1(obj, 5);
MyThread1 t2 = new MyThread1(obj, 20);
t1.start();
t2.start();
}}

You might also like