Java Cant Start Same Thread Again?

Coffee - Multithreading


Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded plan contains two or more parts that can run meantime and each part tin can handle a unlike task at the aforementioned time making optimal use of the available resources specially when your estimator has multiple CPUs.

By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you lot can subdivide specific operations within a single awarding into individual threads. Each of the threads can run in parallel. The OS divides processing fourth dimension not merely amid different applications, just as well amongst each thread within an awarding.

Multi-threading enables you to write in a way where multiple activities can keep meantime in the aforementioned program.

Life Wheel of a Thread

A thread goes through various stages in its life cycle. For instance, a thread is born, started, runs, and then dies. The following diagram shows the complete life bike of a thread.

Java Thread

Following are the stages of the life cycle −

  • New − A new thread begins its life cycle in the new land. Information technology remains in this state until the programme starts the thread. Information technology is also referred to as a born thread.

  • Runnable − After a newly built-in thread is started, the thread becomes runnable. A thread in this country is considered to be executing its task.

  • Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for some other thread to perform a task. A thread transitions back to the runnable country but when another thread signals the waiting thread to go on executing.

  • Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that fourth dimension interval expires or when the issue it is waiting for occurs.

  • Terminated (Expressionless) − A runnable thread enters the terminated state when information technology completes its task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system decide the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more of import to a program and should be allocated processor fourth dimension before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread so you lot can achieve this past implementing a Runnable interface. You volition need to follow three basic steps −

Step one

Equally a first step, you lot need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you volition put your complete business logic inside this method. Following is a simple syntax of the run() method −

public void run( )        

Step ii

Every bit a second footstep, you lot will instantiate a Thread object using the post-obit constructor −

Thread(Runnable threadObj, String threadName);        

Where, threadObj is an instance of a grade that implements the Runnable interface and threadName is the name given to the new thread.

Step 3

Once a Thread object is created, you can start it by calling start() method, which executes a telephone call to run( ) method. Following is a simple syntax of showtime() method −

void start();        

Instance

Here is an instance that creates a new thread and starts running information technology −

grade RunnableDemo implements Runnable {    private Thread t;    private String threadName;        RunnableDemo( Cord name) {       threadName = proper noun;       System.out.println("Creating " +  threadName );    }        public void run() {       System.out.println("Running " +  threadName );       attempt {          for(int i = 4; i > 0; i--) {             System.out.println("Thread: " + threadName + ", " + i);             // Let the thread sleep for a while.             Thread.sleep(l);          }       } take hold of (InterruptedException e) {          System.out.println("Thread " +  threadName + " interrupted.");       }       System.out.println("Thread " +  threadName + " exiting.");    }        public void start () {       Organization.out.println("Starting " +  threadName );       if (t == null) {          t = new Thread (this, threadName);          t.start ();       }    } }  public grade TestThread {     public static void primary(Cord args[]) {       RunnableDemo R1 = new RunnableDemo( "Thread-1");       R1.start();              RunnableDemo R2 = new RunnableDemo( "Thread-2");       R2.start();    }    }        

This will produce the following outcome −

Output

Creating Thread-1 Starting Thread-ane Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, iv Running Thread-2 Thread: Thread-2, iv Thread: Thread-i, 3 Thread: Thread-two, 3 Thread: Thread-1, two Thread: Thread-2, ii Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-one exiting. Thread Thread-ii exiting.        

Create a Thread by Extending a Thread Form

The second way to create a thread is to create a new class that extends Thread class using the following two elementary steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

Pace ane

You will demand to override run( ) method available in Thread class. This method provides an entry point for the thread and you lot will put your consummate business logic within this method. Following is a elementary syntax of run() method −

public void run( )        

Step 2

One time Thread object is created, you tin starting time information technology by calling showtime() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void starting time( );        

Example

Here is the preceding program rewritten to extend the Thread −

class ThreadDemo extends Thread {    private Thread t;    individual String threadName;        ThreadDemo( Cord proper noun) {       threadName = name;       System.out.println("Creating " +  threadName );    }        public void run() {       System.out.println("Running " +  threadName );       try {          for(int i = four; i > 0; i--) {             Organization.out.println("Thread: " + threadName + ", " + i);             // Let the thread sleep for a while.             Thread.slumber(50);          }       } catch (InterruptedException eastward) {          Arrangement.out.println("Thread " +  threadName + " interrupted.");       }       Organisation.out.println("Thread " +  threadName + " exiting.");    }        public void start () {       System.out.println("Starting " +  threadName );       if (t == cipher) {          t = new Thread (this, threadName);          t.first ();       }    } }  public form TestThread {     public static void main(String args[]) {       ThreadDemo T1 = new ThreadDemo( "Thread-i");       T1.get-go();              ThreadDemo T2 = new ThreadDemo( "Thread-2");       T2.start();    }    }        

This will produce the following event −

Output

Creating Thread-ane Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-ii Thread: Thread-2, four Thread: Thread-ane, iii Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, two Thread: Thread-ane, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-ii exiting.        

Thread Methods

Following is the listing of important methods available in the Thread class.

Sr.No. Method & Description
one

public void outset()

Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.

2

public void run()

If this Thread object was instantiated using a carve up Runnable target, the run() method is invoked on that Runnable object.

3

public terminal void setName(String proper name)

Changes the proper noun of the Thread object. There is too a getName() method for retrieving the proper noun.

4

public final void setPriority(int priority)

Sets the priority of this Thread object. The possible values are between 1 and x.

five

public concluding void setDaemon(boolean on)

A parameter of truthful denotes this Thread as a daemon thread.

vi

public last void join(long millisec)

The current thread invokes this method on a second thread, causing the current thread to block until the 2d thread terminates or the specified number of milliseconds passes.

7

public void interrupt()

Interrupts this thread, causing it to go on execution if information technology was blocked for any reason.

viii

public terminal boolean isAlive()

Returns true if the thread is live, which is any time after the thread has been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the Thread grade are static. Invoking one of the static methods performs the operation on the currently running thread.

Sr.No. Method & Clarification
1

public static void yield()

Causes the currently running thread to yield to whatsoever other threads of the same priority that are waiting to be scheduled.

2

public static void sleep(long millisec)

Causes the currently running thread to cake for at least the specified number of milliseconds.

3

public static boolean holdsLock(Object x)

Returns true if the current thread holds the lock on the given Object.

4

public static Thread currentThread()

Returns a reference to the currently running thread, which is the thread that invokes this method.

5

public static void dumpStack()

Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Example

The post-obit ThreadClassDemo plan demonstrates some of these methods of the Thread class. Consider a course DisplayMessage which implements Runnable

// File Name : DisplayMessage.java // Create a thread to implement Runnable  public grade DisplayMessage implements Runnable {    private Cord message;        public DisplayMessage(String message) {       this.message = message;    }        public void run() {       while(true) {          System.out.println(message);       }    } }        

Following is another grade which extends the Thread course −

// File Proper name : GuessANumber.java // Create a thread to extentd Thread  public class GuessANumber extends Thread {    private int number;    public GuessANumber(int number) {       this.number = number;    }        public void run() {       int counter = 0;       int gauge = 0;       do {          guess = (int) (Math.random() * 100 + 1);          Organization.out.println(this.getName() + " guesses " + approximate);          counter++;       } while(estimate != number);       System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");    } }        

Post-obit is the main programme, which makes use of the above-defined classes −

// File Proper noun : ThreadClassDemo.coffee public course ThreadClassDemo {     public static void principal(String [] args) {       Runnable hello = new DisplayMessage("Howdy");       Thread thread1 = new Thread(howdy);       thread1.setDaemon(true);       thread1.setName("hello");       Organisation.out.println("Starting hello thread...");       thread1.start();              Runnable farewell = new DisplayMessage("Goodbye");       Thread thread2 = new Thread(good day);       thread2.setPriority(Thread.MIN_PRIORITY);       thread2.setDaemon(true);       Arrangement.out.println("Starting goodbye thread...");       thread2.start();        System.out.println("Starting thread3...");       Thread thread3 = new GuessANumber(27);       thread3.start();       try {          thread3.join();       } catch (InterruptedException e) {          Organisation.out.println("Thread interrupted.");       }       Organization.out.println("Starting thread4...");       Thread thread4 = new GuessANumber(75);              thread4.start();       System.out.println("primary() is ending...");    } }        

This volition produce the following result. Y'all can try this example again and again and you will become a different issue every time.

Output

Starting hello thread... Starting goodbye thread... Hello Hello Howdy Hello Hello Hullo Bye Goodbye Goodbye Farewell Goodbye .......        

Major Java Multithreading Concepts

While doing Multithreading programming in Coffee, you would need to take the following concepts very handy −

  • What is thread synchronization?

  • Handling interthread communication

  • Treatment thread deadlock

  • Major thread operations

Useful Video Courses


Java Date and Time Online Training

Video

Java Servlet Online Training

Video

JavaScript Online Training

Video

Java Essential Training

Video

Java Essentials Online Training

Video

rowlandagirdly.blogspot.com

Source: https://www.tutorialspoint.com/java/java_multithreading.htm

0 Response to "Java Cant Start Same Thread Again?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel