Thread (Java)
From StudyWiki
This page, Thread (Java), is about the Java class Thread, for general information on threads, go to Thread
Contents |
Overview
Extending Java Thread Class
public class ExampleThread extends Thread {
int parameter;
ExampleThread(int para){parameter = para;}
public void run() {
... // what should the thread do?
}
}
Instantiating and Starting a Thread
- Threads are instantiated like any other object
ExampleThread t = new ExampleThread(10);
Creating a Thread within a ThreadGroup
Thread(ThreadGroup group,Runnable target)
or
Thread(ThreadGroup group);
where:
- group
- is the ThreadGroup object you want to create the Thread within.
Thread Methods
- start()
- Causes concurrent execution to begin.
- JVM will call this Threads run() method within its thread.
- run()
- Executes the run() method directly, without concurrency
- sleep(long ms)
- Cease execution of current thread for ms milliseconds.
- yield()
- Causes the thread to temporarily pause and allow other threads to execute.
- Useful for threads that use a lot of computational time as it forces the current thread to stop and give others a chance to run.
start() vs. run()
- start() initiates concurrent execution.
- run() calls the Threads run() method sequentially.
- For 2 Threads, t1 and t2
- if their start() methods are called, they will interleave.
t1.start(); t2.start();
- if their run() methods are called, t1 will be executed, and when it has completed, t2 will be executed.
- there will be no interleaving
t1.run(); t2.run();
- if their start() methods are called, they will interleave.
Thread Example
class ExampleThread extends Thread {
int _id;
ExampleThread(int id1) {
id = id1;
}
public void run() {
System.out.println("This is thread: " + id);
}
public static void main(String[] args) {
ExampleThread t1 = new ExampleThread(42);
ExampleThread t2 = new ExampleThread(43);
ExampleThread t3 = new ExampleThread(44);
t1.start();
t2.start();
t3.start();
System.out.println("All threads have terminated.");
}
}
The possible output of this code is:
This is thread 42 This is thread 43 All threads have terminated. This is thread 44
- this is because the threads interleave
