Threads: Creating A Thread
Threads: Creating A Thread
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(); }
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()); } }
} 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()); } }
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; } }
} 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;
} }
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."); } }
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) {
} }
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.