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

Threads

Uploaded by

Abinet Bizuayehu
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)
5 views

Threads

Uploaded by

Abinet Bizuayehu
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/ 43

Threads

• Unlike many other computer languages, Java


provides built-in support for multithreaded
programming.
• A multithreaded program contains two or more
parts that can run concurrently.
• Each part of such a program is called a thread, and
each thread defines a separate path of execution.
• Thus, multithreading is a specialized form of
multitasking.
Continued…
• Multithreading - The ability of an OS to support
multiple, concurrent paths of execution within a
single process
• The unit of resource ownership is referred to as
a process or task
• The unit of dispatching is referred to as a thread
or lightweight process
Continued…
• There are two types of multitasking:
– process-based, and
– thread-based
• A process is a program that is executing.
• Thus process-based is multitasking is the
feature that allows computer to run two or
more programs concurrently.
Continued…
• In a thread-based multitasking environment,
the thread is the smallest unit of displaceable
code.
• This means that a single program can perform
two or more tasks simultaneously.
• Multithreading enables you to write very
efficient program that make maximum use of
the CPU, because idle time can be kept
minimum.
Threads
Advantages of threads over processes
• Takes less time to create a new thread than a
process
• Less time to terminate a thread than a process
• Switching between two threads takes less
time than switching between processes
• Threads enhance efficiency in communication
between programs
Thread states
• One of the benefits of threads in Java is that
one thread can run without affecting the
other.
• One thread can pause without stopping other
parts of your program.
• When a thread blocks in a Java program, only
the single thread that is blocked pauses.
• All other threads continue to run.
Continued…
• Threads exist in several states.
• A thread can be running.
• It can be ready to run as soon as it gets CPU time.
• A running thread can be suspended, which temporarily
suspends its activity.
• A suspended program can be resumed, allowing it to
pick up where it is left off.
• A thread can be blocked when waiting for a resource.
• At anytime, a thread can be terminated, which halts its
execution immediately.
• Once terminated, a thread can not be resumed.
Thread priorities
• Java assigns to each thread a priority that
determines how that thread should be treated
with respect to others.
• Thread priorities are integers that specify the
relative priority of one thread to another.
Thread class and runnable interface
• Multithreaded programming can be done in
Java by using interfaces and classes in
java.lang.Thread package.
• To create a new thread, your program will
either extend or implement the Runnable
interface.
• The thread class defines several methods that
help manage threads.
Continued…
• These are:
The main thread
• When a Java program starts up, one thread begins
immediately.
• This is usually called the main thread of your
program, because it is the one that is executed
when your program begins.
• This thread is important for the following reasons
– It is the thread from which other ”child” threads will be
spawned
– Often, it must be the last thread to finish execution
because it performs various shutdown actions
Continued…
• Although the main thread is created automatically
when your program is created, it can be controlled
though a Thread object.
• To do so, you must obtain a reference to it by
calling the method currentThread(), which is a
public static member of Thread.
• This method returns a reference to the thread in
which it is called.
• Once you have a reference to the main thread, you
can control it just like any other thread.
Continued…
• Class CurrentThreadDemo{
• Public static void main(String[] args){
• Thread t=thread.currentThread();
• System.out.println(“current thread:”+t);
• //change the name of the thread
• t.setName(“My Thread”);
• System.out.println(“After Name change:”+t);
• try{
• for(int n=5; n>0;n--){
• System.out.println(n);
• Thread.sleep(100);
• }
• }catch(InterruptedException e){
• System.out.println(“Main thread interrupted”);
• }
• }
• }
Creating thread
• There are two ways to create our own Thread
object:
– Subclassing the Thread class and instantiating a
new object of that class.
– Implementing the Runnable interface
• In both cases the run() method should be
implemented
Extending thread
• The first way to create a thread is to create a
new class that extends Thread, and then to
create an instance of that class.
• The extending class must override the run()
method, which the entry point for the new
thread.
• It must also start() to begin execution of the
new thread.
Continued…
• Class NewThread extends Thread{
• NewThread(){
• Super(“Demo Thread”);
• Sysytem.out.println(“child thread:”+this);
• Start();
• Public void run(){
• try{
• for(int i=5; i>0;i--){
• System.out.println(“child thread:” +i);
• Thread.sleep(500);
• }
• }catch(InterruptedException e){
• System.out.println(“child interrupted”);
• }
• System.out.println(“Exiting child thread”);
• }}
• Class ExtendThread{
• Public static void main(String[] args){
• New NewThread();
• try{
• for(int i=5;i>0;i--){
• System.out.println(“Main thread :”+i);
• Thread.sleep(1000);
• }
• }catch(Interrupted e){
• System.out.println(“Main thread interrupted”);
• }
• System.out.println(“Main thread exiting”);
Continued…
• class ThreadA extends Thread{

• public void run(){

• for(int i=1; i<100;i++){

• System.out.println("ThreadA running : "+i);


• System.out.println("End of ThreadA");

• }
• }
• }

• class ThreadB extends Thread{

• public void run(){

• for(int i=1;i<100;i++){

• System.out.println("ThreadB running: "+i);


• System.out.println("End of ThreadB");
• }
• }
• }
Continued…
• class ThreadC extends Thread{

• public void run(){

• for(int i=1;i<100;i++){

• System.out.println("ThreadC running");
• System.out.println("End of ThreadC");

• }
• }
• }

• public class ThreadTest{

• public static void main(String[] args){

• ThreadA ta= new ThreadA();


• ThreadB tb= new ThreadB();
• ThreadC tc= new ThreadC();

• ta.start();
• tb.start();
• tc.start();

• for(int j=0;j<40;j++){

• System.out.println("Inside Main: "+j);


• System.out.println("End of Main");
• }

• }
Implementing Runnable
• The easiest way to create a thread is to create a
class that implements the Runnable interface.
• To implement Runnable, a class need only
implement a single method called run(),
– Public void run()
• Inside run(), you will define the code that
constitutes the new thread.
• It is important to understand that run() can call
other methods, use other classes, and declare
variables, just like the main thread can
Continued…
• The only difference is that run() establishes the
entry point for another, concurrent thread of
execution within your program.
• This thread will end when run returns.
• After you create a class that implements Runnable,
you will instantiate an object type of Thread from
within that class.
• After the new thread is created , it will not start
running until you call its start() method, which is
declared within Thread.
Continued…
• Class NewThread implements Runnable{
• Thread T;
• NewThread(){
• T=new Thread(this,”Demo Thread”);
• System.out.println(“Child thread: “+ T);
• T.start();
• }
• Public void run(){
• try{
• for(int i=5;i>0;i--){
• System.out.println(“child thread:”+i)
• Thread.sleep(500);
• }
• }catch(InterruptedException e){
• System.out.println(“Child interrupted”);
• }
• System.out.println(“Exitiing child thread”);
• }
• }
• Public class ThreadDemo{
• Public static void main(String[] args){
• new NewThread();
• try{
• for(int i=5; i>0;i--){
• System.out.println(“Main thread: “+i);
• Thread.sleep(1000);
• }
• }catch(InterruptedException e){
• System.out.println(“Main thread interrupted”);
• }
• System.out.println(“Main thread exitiing”);
• }
THREAD PRIORITY
• In Java, all the thread instances the developer created have the
same priority, which the process will schedule fairly without
worrying about the order.
• Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.
• It is important for different threads to have different priorities.
• It is possible to control the priority of the threads by using the
Java APIs.
• The Thread.setPriority(…) method serves this purpose.
• The Thread class provides 3 constants value for the priority:
• MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10
• The priority range of the thread should be between the
minimum and the maximum number.
Continued…
• class A extends Thread {
• public void run() {
• System.out.println(“Thread A started”);
• for(int i = 1; i <= 4; i++) {
• System.out.println(“\t From ThreadA: i= ” + i);
• }
• System.out.println(“Exit from A”);
• }
• }
• class B extends Thread {
• public void run() {
• System.out.println(“Thread B started”);
• for(int j = 1; j <= 4; j++) {
• System.out.println(“\t From ThreadB: j= ” + j);
• }
• System.out.println(“Exit from B”);
• }
• }
Continued…
• class C extends Thread {
• public void run() {
• System.out.println(“Thread C started”);
• for(int k = 1; k <= 4; k++) {
• System.out.println(“\t From ThreadC: k= ” + k);
• }
• System.out.println(“Exit from C”);
• }
• }
• public class ThreadPriorityDemo {
• public static void main(String args[]) {
• A threadA = new A();
• B threadB = new B();
• C threadC = new C();
Continued…
• threadC.setPriority(Thread.MAX_PRIORITY);
• threadB.setPriority(threadA.getPriority() + 1);
• threadA.setPriority(Thread.MIN_PRIORITY);
• System.out.println(“Started Thread A”);
• threadA.start();
• System.out.println(“Started Thread B”);
• threadB.start();
• System.out.println(“Started Thread C”);
• threadC.start();
• System.out.println(“End of main thread”);
• }
• }
Thread Synchronization
• Threading is a very powerful technique which
is sometimes very hard to control, especially
when it is accessing shared resources.
• In such cases, the threads have to be
coordinated, otherwise it will violate the data
of the whole application.
Continued…
• For example, a printer cannot be used to print
two documents at the same time and if there
are multiple printing requests, threads
managing these printing operations needs to be
coordinated.
• Another example would be simultaneously
operating the same bank account: it is not
correct to do both deposit and withdraw
operations on a bank account at the same time.
Continued…
• 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.
Read/Write Problem
• If one thread tries to read the data and another
thread tries to update the same data, it is known
as read/ write problem, and it leads to inconsistent
state for the shared data.
• This can be prevented by synchronizing access to
the data via Java synchronized keyword. For
example,
public synchronized void update() {

}
Continued…
• It is better to explain the synchronized
approach to access the shared data via a
simple example.
• Consider an example of a bank offering online
access to its customers to perform
transactions on their accounts from anywhere
in the world
Continued…
• If the cheque-receipient happens to withdraw
the money at the same time the original-
account holder deposits the money, both
parties are performing simultaneous
operations on the same account.
• This situation can lead to incorrect operation
on the account
Continued…
• This can be avoided by synchronization, which
ensures that only one person is able to
perform an operation on a shared data at a
time (i.e., in a way operations are sequenced
to avoid data inconsistency problems).
• The following class shows a typical invocation
of banking operations via multiple threads
Synchronization Example
• public class InternetBankingSystem {
• public static void main(String [] args ) {
• Account accountObject = new Account(100);
• new Thread(new DepositThread(accountObject,30)).start();
• new Thread(new DepositThread(accountObject,20)).start();
• new Thread(new DepositThread(accountObject,10)).start();
• new Thread(new WithdrawThread(accountObject,30)).start();
• new Thread(new WithdrawThread(accountObject,50)).start();
• new Thread(new WithdrawThread(accountObject,20)).start();
• } // end main()
• }
Continued…
• public class WithdrawThread implements Runnable {
• private Account account;
• private double amount;
• public WithdrawThread(Account account, double amount) {
• this.account = account;
• this.amount = amount;
• }
• public void run() {
• //make a withdraw
• account.withdraw(amount);
• }
• }//end WithdrawThread class
Continued…
• public class DepositThread implements Runnable {
• private Account account;
• private double amount;
• public DepositThread(Account account, double amount) {
• this.account = account;
• this.amount = amount;
• }
• public void run() {
• //make a deposit
• account.deposit(amount);
• }
• }//end DepositThread class
Continued…
• public class Account {
• private double balance = 0;
• public Account(double balance) {
• this.balance = balance;
• }
• // if ‘synchronized’ is removed, the outcome is unpredictable
• public synchronized void deposit(double amount) {
• if (amount < 0) {
• throw new IllegalArgumentException(“Can’t deposit.”);
• }
• this.balance += amount;
• System.out.println(“Deposit ”+amount+“ in thread” +Thread.currentThread().getId()
• +“, balance is ” +balance);
• }
• // if ‘synchronized’ is removed, the outcome is unpredictable
• public synchronized void withdraw(double amount) {
• if (amount < 0 || amount > this.balance) {
• throw new IllegalArgumentException(“Can’t withdraw.”);
• }
• this.balance -= amount;
• System.out.println(“Withdraw ”+amount+“ in thread ” + Thread.currentThread().getId()
• + “, balance is ”+balance);
• }
• }//end Account class
Continued…
• There are 6 threads that access the same Account
object simultaneously.
• As can be seen, the three deposit threads are
performing deposit operations on an account and
simultaneously three Withdraw threads are
withdrawing from the same account.
• If the account object is not synchronized properly,
the outcome may be unpredictable while these
operations are performing simultaneously.
• To ensure the proper behavior of the application, it
is necessary to synchronize the methods on the
Account class.
Continued…
• The synchronized method will ensure that only
one class can access the data at one time,
other operations have to wait until the first
operation finishes.
• However, if the account class is modified
without the synchronized keyword placed on
the methods that access the balance data,
unpredictable behavior will occur.
If you use Thread class
• public class WithdrawalThread extends Thread {
• private Account account;
• private double amount;
• public WithdrawalThread(Account account, double amount) {
• this.account = account;
• this.amount = amount;
• }
• public void run() {
• //make a withdraw
• account.withdrawal(amount);
• }
• }//
Continued…
• public class DepositThread extends Thread {
• private Account account;
• private double amount;
• public DepositThread(Account account, double amount) {
• this.account = account;
• this.amount = amount;
• }
• public void run() {
• //make a deposit
• account.deposit(amount);
• }
• }//end DepositThread class
Continued…
• public class Account {
• private double balance = 0;
• public Account(double balance) {
• this.balance = balance;
• }
• // if ‘synchronized’ is removed, the outcome is unpredictable
• public synchronized void deposit(double amount) {
• if (amount < 0) {
• throw new IllegalArgumentException("Can’t deposit.");
• }
• this.balance += amount;
• System.out.println("Deposit "+amount+" in thread“ +Thread.currentThread().getId()
• +", balance is " +balance);
• }
• // if ‘synchronized’ is removed, the outcome is unpredictable
• public synchronized void withdrawal(double amount) {
• if (amount < 0 || amount > this.balance) {
• throw new IllegalArgumentException("Can’t withdraw.");
• }
• this.balance -= amount;
• System.out.println("Withdrawal "+amount+" in thread “ + Thread.currentThread().getId()
• + ", balance is "+balance);
• }
• }//end Account class
Continued..
• public class InternetBankingSystem {
• public static void main(String[] args) {
• Account accountObject = new Account(100);

• Thread dt1=new DepositThread(accountObject,30);


• Thread dt2=new DepositThread(accountObject,20);
• Thread dt3=new DepositThread(accountObject,10);
• Thread wt1=new WithdrawalThread(accountObject,30);
• Thread wt2=new WithdrawalThread(accountObject,50);
• Thread wt3=new WithdrawalThread(accountObject,20);

• dt1.start();
• dt2.start();
• dt3.start();
• wt1.start();
• wt2.start();
• wt3.start();
• } // end main()
• }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy