Thread
-> A lightweight process.
Multithreading
->When multiple threads execute
byte-code instruction sequences in the same program, that action is known as
multithreading.
[Example available in bottom section]
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
The thread
can be run by creating an instance of the class and call its start() method
Main thread = new Main();
thread.start();
2) Another
way to create a thread is to implement the Runnable interface
public class Main implements
Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
The thread
can be run by passing an instance of the class to a Thread object's constructor
and then calling the thread's start() method
Main obj = new Main();
Thread
thread = new Thread(obj);
thread.start();
Differences
between "extending" and "implementing" Threads
The major
difference is that when a class extends the Thread class, you cannot extend any
other class, but by implementing the Runnable interface, it is possible to
extend from another class as well
Concurrency
Problems: When the threads and main program are reading and writing the
same variables, the values are unpredictable
Example:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
}
public void run() {
amount++;
}
}
Use
isAlive() to prevent concurrency problems
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
// Wait for the thread to finish
while(thread.isAlive()) {
System.out.println("Waiting...");
}
// Update amount and print its value
System.out.println("Main: " + amount);
amount++;
System.out.println("Main: " + amount);
}
public void run() {
amount++;
}
}
Threads exist in several states. Following are those states:
- New – When we create an instance of Thread class, a thread is in a new state.
- Runnable – The Java thread is in running state.
- Suspended – A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off.
- Blocked – A java thread can be blocked when waiting for a resource.
- Terminated – A thread can be terminated, which halts its execution immediately at any given time. Once a thread is terminated, it cannot be resumed.
Thread class defines several methods that help manage threads.
Method | Meaning |
getName | Obtain thread’s name |
getPriority | Obtain thread’s priority |
isAlive | Determine if a thread is still running |
join | Wait for a thread to terminate [Example available in bottom section] |
run | Entry point for the thread |
sleep | Suspend a thread for a period of time |
start | Start a thread by calling its run method |
public class Data { private String packet; // True if receiver should wait // False if sender should wait private boolean transfer = true; public synchronized void send(String packet) { while (!transfer) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } transfer = false; this.packet = packet; notifyAll(); } public synchronized String receive() { while (transfer) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } transfer = true; notifyAll(); return packet; } } |
public class Sender implements Runnable { private Data data; // standard constructors public void run() { String packets[] = { "First packet", "Second packet", "Third packet", "Fourth packet", "End" }; for (String packet : packets) { data.send(packet); // Thread.sleep() to mimic heavy server-side processing try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } } } |
public class Receiver implements Runnable { private Data load; // standard constructors public void run() { for(String receivedMessage = load.receive(); !"End".equals(receivedMessage); receivedMessage = load.receive()) { System.out.println(receivedMessage); // ... try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } } } |
public static void main(String[] args) { Data data = new Data(); Thread sender = new Thread(new Sender(data)); Thread receiver = new Thread(new Receiver(data)); sender.start(); receiver.start(); } |
No comments:
Post a Comment