0% found this document useful (0 votes)
41 views20 pages

Thread

A thread is a single sequential flow of control within a program that allows for multiple flows to exist simultaneously. There are two main ways to define a thread in Java - by extending the Thread class or implementing the Runnable interface. Threads have lifecycles that involve states such as new, runnable, blocked, waiting, timed waiting, and terminated.

Uploaded by

Nandees july13
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)
41 views20 pages

Thread

A thread is a single sequential flow of control within a program that allows for multiple flows to exist simultaneously. There are two main ways to define a thread in Java - by extending the Thread class or implementing the Runnable interface. Threads have lifecycles that involve states such as new, runnable, blocked, waiting, timed waiting, and terminated.

Uploaded by

Nandees july13
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/ 20

Thread

What is a thread ?
• A sequential (or single-threaded) program is one that, when executed, has only one
single flow of control.
• i.e., at any time instant, there is at most only one instruction (or statement or execution point) that
is being executed in the program.
• A multi-threaded program is one that can have multiple flows of control when executed.
• At some time instance, there may exist multiple instructions or execution points) that are being
executed in the program
• Ex: in a Web browser we may do the following tasks at the same time:
• 1. scroll a page,
• 2. download an applet or image,
• 3. play sound,
• 4 print a page.
• A thread is a single sequential flow of control within a program.
{ A();
{ A(); A1(); A2(); A3(); newThreads {
B1(); B2(); } { A1(); A2(); A3() };
{B1(); B2() }
}
}
Thread ecology in a java
started program
by java from main(String[])

started by main thread

started by B thread

lifetime of C thread
2. Define and launch a java thread
• Each Java Run time thread is encapsulated in a java.lang.Thread instance.
• Two ways to define a thread:
1. Extend the Thread class
2. Implement the Runnable interface :
package java.lang;
public interface Runnable { public void run() ; }
• Steps for extending the Thread class:
1. Subclass the Thread class;
2. Override the default Thread method run(), which is the entry point of the thread,
like the main(String[]) method in a java program.
Define a thread
• Extends Thread
public class Print2Console extends Thread {
public void run() { // run() is to a thread what main() is to a java program
for (int b = -128; b < 128; b++) out.println(b); }
… // additional methods, fields …
}
• Impement the Runnable interface if you need a parent class:
// by extending JTextArea we can reuse all existing code of JTextArea
public class Print2GUI extends JTextArea implements Runnable {
public void run() {
for (int b = -128; b < 128; b++) append( Integer.toString(b) + “\n” ); }
}
Some thread property access methods

• int getID() // every thread has a unique ID, since jdk1.5


• String getName(); setName(String)
• // get/set the name of the thread
• int getPriority() ; setPriority(int) // thread has priority in [0, 31]
• Thread.State getState() // return current state of this thread
• Join()
• Wait for thread to terminate
• Run()
• Entry point for thread
• Start()
• Start the method by calling its method
• boolean isAlive()
• Tests if this thread has been started and has not yet died. .
• boolean isDaemon()
• Tests if this thread is a daemon thread.
• boolean isInterrupted()
• Tests whether this thread has been interrupted.
State methods for current thread accesses

• static Thread currentThread()


• Returns a reference to the currently executing thread object.
• static boolean holdsLock(Object obj)
• Returns true if and only if the current thread holds the monitor lock on the specified
object.
• static boolean interrupted()
• Tests whether the current thread has been interrupted.
• static void sleep( [ long millis [, int nanos ]] )
• Causes the currently executing thread to sleep (cease execution) for the specified time.
• static void yield()
• Causes the currently executing thread object to temporarily pause and allow other
threads to execute.
Method 1:
Class Thread
Example 1:
class MyThread1 extends Thread {
public void run()
{
System.out.println("Thread1 is running");
}
}

class MyThread2 extends Thread {

public void run()


{
System.out.println("Thread2 is running");
}
}

class GFG {

public static void main(String[] args)


{
MyThread1 obj1 = new MyThread1();
MyThread2 obj2 = new MyThread2();
obj1.start();
obj2.start();
}
}
Example 2
public class SimpleThread extends Thread {
public SimpleThread(String str) { super(str); }
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try { // at this point, current thread is ‘this’.
Thread.sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
} }
0 Thread-0
0 Thread-1
output
1 Thread-1
1 Thread-0
2 Thread-0
2 Thread-1
3 Thread-1
3 Thread-0
4 Thread-0
4 Thread-1
5 Thread-1
5 Thread-0
6 Thread-0
6 Thread-1
7 Thread-1
7 Thread-0
8 Thread-0
8 Thread-1
9 Thread-1
9 Thread-0
DONE! Thread-0
DONE! Thread-1
Method 2:
Runnable interface
import java.io.*;
import java.util.*;
class MyThread1 implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread1");

try {
Thread.sleep(1000); }
catch (Exception e) {
} } } }
class MyThread2 implements Runnable {
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Thread2");
try {
Thread.sleep(1000);
}

catch (Exception e) {
} } } }
public class GFG {
public static void main(String[] args)
{
Runnable obj1 = new MyThread1();
Runnable obj2 = new MyThread2();
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start();
t2.start();
} }
output
Thread1
Thread2
Thread1
Thread2
Thread1
Thread2
Thread1
Thread2
Thread1
Thread2
Example 2:
output
Example 3
output
Lifecycle of thread

A thread lies only in one of the shown states at any instant:


New State
Runnable State
Blocked State
Waiting State
Timed Waiting State
Terminated State

You might also like