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

Threads: Creating A Thread

There are two main ways to create threads in Java: 1. Extend the Thread class and override the run() method. 2. Implement the Runnable interface and override the run() method. Once a thread is created via one of these two methods, it must be started by calling the start() method. The run() method contains the code that is executed by the thread. Threads can be in one of six states: new, runnable, blocked, waiting, timed_waiting, or terminated. Multithreading allows multiple tasks to execute concurrently within a single program using multiple threads.

Uploaded by

Sunny_Bargava
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Threads: Creating A Thread

There are two main ways to create threads in Java: 1. Extend the Thread class and override the run() method. 2. Implement the Runnable interface and override the run() method. Once a thread is created via one of these two methods, it must be started by calling the start() method. The run() method contains the code that is executed by the thread. Threads can be in one of six states: new, runnable, blocked, waiting, timed_waiting, or terminated. Multithreading allows multiple tasks to execute concurrently within a single program using multiple threads.

Uploaded by

Sunny_Bargava
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

Threads

Creating a Thread:
Thread is a basic processing unit to which an operating system allocates processor time, and more than one thread can be executing code inside a process Every Java program has at least one thread, the thread that executes the Java program. It is created when you invoke the static main method of your Java class There are two ways to create a thread: 1. 2. 3. 4. 5. Extend the java.lang.Thread class Implement the java.lang.Runnable interface Once you have a Thread object, you call its start method to start the thread. When a thread is started, its run method is executed. Once the run method returns or throws an exception, the thread dies and will be garbage-collected.

Every Thread has a state and a Thread can be in one of these six states 1. 2. 3. 4. new. A state in which a thread has not been started. runnable. A state in which a thread is executing. blocked. A state in which a thread is waiting for a lock to access an object. waiting. A state in which a thread is waiting indefinitely for another thread to perform an action. 5. timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action. 6. terminated. A state in which a thread has exited. The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED
The Runnable Interface Signature public interface Runnable { void run(); }

Implementing the Runnable Interface


The procedure for creating threads based on the Runnable interface is as follows: 1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object. 2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. 3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. 4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception. Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.
class RunnableThread implements Runnable { Thread runner; public RunnableThread() { } public RunnableThread(String threadName) { runner = new Thread(this, threadName); // (1) Create a new System.out.println(runner.getName()); runner.start(); // (2) Start the thread. } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread()); } } public class RunnableExample { public static void main(String[] args) { Thread thread1 = new Thread(new RunnableThread(), "thread1"); Thread thread2 = new Thread(new RunnableThread(), "thread2");

thread.

RunnableThread thread3 = new RunnableThread("thread3"); //Start the threads thread1.start(); thread2.start(); try { //delay for one second Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } //Display info about the main thread System.out.println(Thread.currentThread()); } }

Output thread3 Thread[thread1,5,main] Thread[thread2,5,main] Thread[thread3,5,main] Thread[main,5,main]private

Extending Thread Class


The procedure for creating threads based on extending the Thread is as follows: 1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread. 2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call. 3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running. Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

class XThread extends Thread { XThread() {

} XThread(String threadName) { super(threadName); // Initialize thread. System.out.println(this); start(); } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread().getName()); } } public class ThreadExample { public static void main(String[] args) { Thread thread1 = new Thread(new XThread(), "thread1"); Thread thread2 = new Thread(new XThread(), "thread2"); // The below 2 threads are assigned default names Thread thread3 = new XThread(); Thread thread4 = new XThread(); Thread thread5 = new XThread("thread5"); //Start the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); try { //The sleep() method is invoked on the main thread to cause a one second delay. Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } //Display info about the main thread System.out.println(Thread.currentThread()); } }

Output Thread[thread5,5,main] thread1 thread5 thread2 Thread-3 Thread-2 Thread[main,5,main]

Creating Thread: Deriving a Subclass of Thread:

import java.io.IOException; class TryThread extends Thread { public TryThread(String firstName, String secondName, long delay) { this.firstName = firstName; this.secondName = secondName; aWhile = delay; setDaemon(true); } public void run() { try { while (true) { System.out.print(firstName); sleep(aWhile); System.out.print(secondName + "\n"); } } catch (InterruptedException e) { System.out.println(firstName + secondName + e); } } private String firstName; private String secondName; private long aWhile; } public class MainClass { public static void main(String[] args) { Thread first = new TryThread("A ", "a ", 200L); Thread second = new TryThread("B ", "b ", 300L); Thread third = new TryThread("C ", "c ", 500L); System.out.println("Press Enter when you have had enough...\n"); first.start(); second.start(); third.start(); try { System.in.read(); System.out.println("Enter pressed...\n"); } catch (IOException e) { System.out.println(e); } return; } }

Creating Thread Objects: Implementing the run() Method in Runnable interface:


import java.io.IOException; class TryThread implements Runnable { public TryThread(String firstName, String secondName, long delay) { this.firstName = firstName; this.secondName = secondName; aWhile = delay;

} public class MainClass { public static void main(String[] args) { Thread first = new Thread(new TryThread("A ", "a ", 200L)); Thread second = new Thread(new TryThread("B ", "b ", 300L)); Thread third = new Thread(new TryThread("C ", "c ", 500L)); System.out.println("Press Enter when you have had enough...\n"); first.start(); second.start(); third.start(); try { System.in.read(); System.out.println("Enter pressed...\n"); } catch (IOException e) { System.out.println(e); } System.out.println("Ending main()"); return; } }

} public void run() { try { while (true) { System.out.print(firstName); Thread.sleep(aWhile); System.out.print(secondName + "\n"); } } catch (InterruptedException e) { System.out.println(firstName + secondName + e); } } private String firstName; private String secondName; private long aWhile;

Create a second thread:


class NewThread implements Runnable { Thread t; NewThread() { t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the 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.");

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

Create a second thread by extending Thread :


class NewThread extends Thread { NewThread() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); // Start the 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."); }

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

Create 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 } 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 { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } } } System.out.println("Main thread exiting.");

The following figure shows the methods that are members of the Object and Thread Class.

Multithreading:
Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously Asynchronous treads run independently of each other. Synchronous treads can exchange messages with each other or wait for an action to occur in other thread(s).

Multithreading consists of multiple sets of statements which can be run in parallel. Although a single processor can run only one thread at a time, strategies such as timeslicing and interrupt methods (depending on the scheduling method) simulate threads running simultaneously

Multitasking:
Multitasking is performing two or more tasks at the same time. Nearly all operating systems are capable of multitasking by using one of two multitasking techniques: process-based multitasking and thread-based multitasking. Thread-based multitasking is having a program perform two tasks at the same time. For example, a word processing program can check the spelling of words in a document while you write the document. This is thread-based multitasking.

Process-based multitasking as working with multiple programs at the same time For Example working with two different programs word and paint at same time is also known as process-based Multitasking A good way to remember the difference between process-based multitasking and thread-based multitasking is to think of process-based as working with multiple programs and thread-based as working with parts of one program. The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU as the engine of your car. Your engine keeps running regardless of whether the car is moving. Your objective is to keep your car moving as much as possible so you can get the most miles from a gallon of gas. An idling engine wastes gas.

Daemon Thread:
A daemon thread is a thread that runs for the benefit of other threads. Daemon threads run in the background and do not prevent a program from terminating. For example, the garbage collector is a daemon thread. Daemon threads belong to the system and not to the process that spawned them. A program can include a mixture of daemon and non-daemon threads. The Java virtual machine will exit when only daemon threads remain.

You might also like