28 Aug — Thread introduction
Motivations for concurrency
- Keep CPU busy while I/O tasks underway (e.g., process data from file while reading disk, Web server)
- Take advantage of parallelism in CPU design (e.g., multicore, hyperthreading)
- Multiple-CPU computers for high-performance applications (e.g., scientific computing & supercomputers, Google)
Threads
The most common technique for concurrency in small installations is threads. Each thread is an independent sequence of computation, which runs at an unpredictable, variable speed. The number of threads allowed is unbounded (regardless of # processors).
Simple thread example
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.Scanner;
class Job {
private int query;
public Job(int k) {
query = k;
}
public void process() {
for (int i = 2; i * i <= query; i++) {
if (query % i == 0) {
System.out.println(query + " is divisible by " + i);
return;
}
}
System.out.println(query + " is prime");
}
}
class JobProcessor implements Runnable {
private BlockingQueue<Job> jobs;
public JobProcessor(BlockingQueue<Job> j) {
jobs = j;
}
public void run() {
while (true) {
Job j;
try {
j = jobs.take();
j.process();
} catch (InterruptedException e) {
System.err.println("interrupted in jobs.take");
}
}
}
}
public class Main {
public static void main(String[] args) {
BlockingQueue<Job> jobs = new LinkedBlockingQueue<Job>();
for (int i = 0; i < 100; i++) {
JobProcessor p = new JobProcessor(jobs);
Thread t = new Thread(p);
t.start();
}
Scanner in = new Scanner(System.in);
while (true) {
int k = in.nextInt();
try {
jobs.put(new Job(k));
} catch (InterruptedException e) {
System.err.println("interrupted in jobs.put");
}
}
}
}