28 Aug — Thread introduction

Motivations for concurrency

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 = 2i * i <= queryi++) {
            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<Jobjobs;

    public JobProcessor(BlockingQueue<Jobj) {
        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<Jobjobs = new LinkedBlockingQueue<Job>();
        for (int i = 0i < 100i++) {
            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");
            }
        }
    }
}