60. ProducerConsumer.java
public class ProducerConsumer {
public static void main(String[] args) {
MyQueue queue = new MyQueue(3);
Producer producer = new
Producer(queue);
Consumer consumer = new
Consumer(queue);
producer.start();
consumer.start();
}
}
61. MyQueue.java(1)
public class MyQueue {
int[] intbuf;
int start;
int count;
public MyQueue(int size) {
intbuf = new int[size];
start = 0;
count = 0;
}
public synchronized void put(int n) throws InterruptedException {
while (count >= intbuf.length) {
System.out.println(Thread.currentThread().getName() + " wait : バッ
ファの空きを待つ");
wait();
}
int end = (start + count) % intbuf.length;
intbuf[end] = n;
count++;
notifyAll();
}
62. MyQueue.java(2)
public synchronized int take() throws InterruptedException {
while (count == 0) {
System.out.println(Thread.currentThread().getName() + "
wait : データを待つ");
wait();
}
int n = intbuf[start];
start = (start + 1) % intbuf.length;
count--;
notifyAll();
return n;
}
}
63. Producer.java(1)
public class Producer extends Thread {
static final int END = -1;
MyQueue queue = null;
public Producer(MyQueue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
int n = produce(i);
queue.put(n);
}
queue.put(Producer.END);
} catch (InterruptedException e) {
System.out.println(e);
}
};
80. Job.java
public class Job {
int num;
public Job(int n) {
num = n;
}
public void work() {
System.out.println(this + " is working." );
try {
int n = (int) Math.random() * 10000;
Thread.sleep(n);
} catch (InterruptedException e) {
}
}
public String toString() {
return "[Job " + num + "]";
}
}
81. SingleThreadProgram.java
public class SingleThreadProgram {
Job[] jobs;
public SingleThreadProgram(int jobcount) {
jobs = new Job[jobcount];
for (int i = 0; i< jobcount; i++) {
jobs[i] = new Job(i);
}
}
public void workAllJobs() {
for (int i = 0; i < jobs.length; i++) {
jobs[i].work();
}
}
public static void main(String[] args) {
SingleThreadProgram self = new SingleThreadProgram(10);
while(true) {
self.workAllJobs();
}
}
}