Saturday, August 5, 2023

Multithreading in Java

 

Multithreading in Java


Multithreading is a Specialized form of Multitasking.

There are two distinct types of multitasking:

vProcess based

Process based Multitasking enables you to run the java compiler at the same time that you are using a test editor.

vThread based

Thread based multitasking environment ,the thread is the smallest unit of dispatchable code.

Threads are light weight

Creating a Thread

Method

Meaning

getName

Obtain a thread's name.

getPriority

Obtion a thread's priority.

isAlive

Determing if a thread is still running.

join

Wait for a thread to terminate.

run

Entry point for a period of time.

sleep

Suspend a thread for a period of time.

start

Start a thread by calling its run method.

 

Implementing Runnable

The easiest way to create a thread is to create a class that implements the Runnable interface.

public void run()

Inside run(), you wil 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. 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 of type Thread from within the class. Thread defines several constructors.

Thread(Runnable threadOb,String threadName)

In this constructor, threadOb is an instance of a class that implments the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by thread Name.

 

After the new thread is created, it wil not start running until you call its start() method, which is declared within Thread. The start() method is shown here:

Void start()

Creating a Thread

File name:  NewThread.java

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("Existing Child Thread.");

}

}

File name: ThreadDemo.java

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 exiting");

}

}


Output



Extending Thread

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.

Example

//Create a second thread by extending Thread

File name: NewThread.java

class NewThread extends Thread{

 NewThread(){

        //Create a new, second thread

super("Demo Thread");

System.out.println("Child thread:"+this);

start();//start the thread

}

//This is the entry point for the second thread.

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.");

    }

 }

File name: ExtendThread.java

class ExtendThread{

  public static void main(String args[]){

    new NewThread();//create a new thread

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 exiting.");

 }

}

 

Output


 

Creating Multiple Threads

Two threads: Main Thread and Child Thread

Example

      // Create multiple threads.

  File name: NewThread.java

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." );

}

}

 File name: MultiThreadDemo.java

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.");

}

}       

Output

 



isAlive() and join()

isAlive() method helps to determine whether a thread has finished or not.

File name: NewThread.java

class NewThread implements Runnable{

String name;

Thread t;

NewThread(String threadname){

name=threadname;

t=new Thread(this,name);

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

t.start();

}

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.");

}

}

File name: DemoJoin.java

class DemoJoin{

public static void main(String args[]){

NewThread ob1=new NewThread("One");

NewThread ob2=new NewThread("Two");

NewThread ob3=new NewThread("Three");

System.out.println("Thread One is alive: "+ob1.t.isAlive());

System.out.println("Thread Two is alive: "+ob2.t.isAlive());

System.out.println("Thread Three is alive: "+ob3.t.isAlive());

try{

System.out.println("Waiting for threads to finish");

ob1.t.join();

ob2.t.join();

ob3.t.join();

}catch(InterruptedException e){

System.out.println("Main Thread Interrupted");

}

System.out.println("Thread One is alive: "+ob1.t.isAlive());

System.out.println("Thread Two is alive: "+ob2.t.isAlive());

System.out.println("Thread Three is alive: "+ob3.t.isAlive());

System.out.println("Main Thread exiting");

}

}

 

Output


Thread Priorities

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.

Higher priority threads get more CPU time than Lower priority threads.

File name: Clicker.java

class Clicker implements Runnable{

int click=0;

Thread t;

private volatile boolean running=true;

public Clicker(int p){

t=new Thread(this);

t.setPriority(p);

}

public void run(){

while(running){

click++;

}

}

public void stop(){

running=false;

}

public void start(){

t.start();

}

}

File name: HiLoPri.java

class HiLoPri{

public static void main(String args[]){

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

Clicker hi=new Clicker(Thread.NORM_PRIORITY+2);

Clicker lo=new Clicker(Thread.NORM_PRIORITY-2);

lo.start();

hi.start();

try{

Thread.sleep(10000);

}

catch(InterruptedException e){

System.out.println("Main Thread interrupted.");

}

lo.stop();

hi.stop();

try{

hi.t.join();

lo.t.join();

}

catch(InterruptedException e){

System.out.println("InterruptedException caught");

}

System.out.println("Low-priority thread"+lo.click);

System.out.println("High-priority thread"+hi.click);

}

}

 

Output


 

 Synchronization

When two or more threads need access to a shared resources, they need some way to ensure that the resources will be used by only one thread at a time. The process by which this is achieved is called Synchronization.

Key to synchronization is the concept of the monitor.

File name: Callme.java

class Callme{

void call(String msg){

System.out.println("["+msg);

try{

Thread.sleep(1000);

}

catch(InterruptedException e){

System.out.println("Interrupted");

}

System.out.println("]");

}

}

File name: Caller.java

class Caller implements Runnable{

String msg;

Callme target;

Thread t;

public Caller(Callme targ,String s){

target=targ;

msg=s;

t=new Thread(this);

t.start();

}

public void run(){

target.call(msg);

}

}

File name: Synch.java

class Synch{

public static void main(String args[]){

Callme target=new Callme();

Caller ob1=new Caller(target,"Hello");

Caller ob2=new Caller(target,"Synchronized");

Caller ob3=new Caller(target,"World");

try{

ob1.t.join();

ob2.t.join();

ob3.t.join();

}

catch(InterruptedException e){

System.out.println("Interrupted");

}

}

}

 

Output

 


 

Thread Infinite

File name: Q.java

class Q{

int n;

boolean valueSet=false;

synchronized int get(){

if(!valueSet)

try{

wait();

}

catch(InterruptedException e){

System.out.println("InterruptedException caught");

}

System.out.println("Got:"+n);

valueSet=false;

notify();

return n;

}

synchronized void put(int n){

if(valueSet)

try{

wait();

}catch(InterruptedException e){

System.out.println("InterruptedException caught");

}

this.n=n;

valueSet=true;

System.out.println("Put:"+n);

notify();

}

}

File name: Producer.java

class Producer implements Runnable{

Q q;

Producer(Q q){

this.q=q;

new Thread(this,"Producer").start();

}

public void run(){

int i=0;

while(true){

q.put(i++);

}

}

}

 

File name: Consumer.java

class Consumer implements Runnable{

Q q;

Consumer(Q q){

this.q=q;

new Thread(this,"Consumer").start();

}

public void run(){

while(true){

q.get();

}

}

}

 

File name: PCFixed.java

class PCFixed{

public static void main(String args[]){

Q q=new Q();

new Producer(q);

new Consumer(q);

System.out.println("Press Ctrl+c to stop.");

}

}

 

Output

 


 

0 comments:

Post a Comment