[OS] Thread - Java Thread
28 Apr 2020
There are two ways to create thread in Java:
- extends Thread class, overrides run() method
- implements Runnable class, overrides run() method
Implementing Runnable is relatively simple:
@Data
class Sum {
private int sum;
}
class Summation implements Runnable
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue) {
this.upper = upper;
this.sumValue = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++) {
sum += i;
}
sumValue.setSum(sum);
}
}
After creating Thread, we have to run thread with start() method (NEVER run thread with run() method directly). start() methods works like this:
- Allocates Memory
- Initialize Thread on JVM
- calls run() method, let thread have opportunity to run by JVM
For example:
public class Driver {
public static void main(String[] args) {
Sum sumObj = new Sum();
int upper = Integer.parseInt(args[0]);
Thread thrd = new Thread(new Summation(upper, sumObj));
thrd.start();
try {
thrd.join();
System.out.println("The sum of " + upper + " is " + sumObj.getSum());
} catch (InterruptedException ie) {
// do nothing
}
}
}
Java separates thread type to
- Daemon
- Non-Daemon
Key differences is that JVM terminates after all non-daemon work terminates. On JVM start, it creates several daemon threads like garbage collector. Creating daemon thread can be done by calling:
thrd.setDaemon(true);
JAVA Thread Status
- new : Thread object created with new …(); call
- runnable : when start() command calls thread’s run() method
- blocked (not runnable) : io(), or sleep(), ….
- running : thread is on work
- terminated : thread done its job
Appendix: A Multithread Solution to the Producer-Consumer Problem
import java.util.Date;
public class Factory {
public static void main(String args[]) {
Channel<Date> queue = new MessageQueue<Date>();
Thread producer = new Thread(new Producer(queue));
Thread consumer = new Thread(new Consumer(queue));
producer.start();
consumer.start();
}
}