スレッド+スタックは生産者の消費者関係を簡単に実現する
3230 ワード
//
package test_produce;
public class Produce implements Runnable{
Stack_used su;
public Produce(){}
public Produce(Stack_used su){
this.su = su;
}
// 100
public void run(){
for(int i = 0; i < 100; i++){
su.pushOne(i);
}
}
}
//
package test_produce;
public class Consume implements Runnable{
Stack_used su;
public Consume(){}
public Consume(Stack_used su){
this.su = su;
}
public void run(){
for(int i = 0; i < 100; i++){
su.popOne();
}
}
}
//
package test_produce;
import java.util.Stack;
public class Stack_used {
public static final int SIZE = 5;//
Stack<Integer> stack ;
public Stack_used(){
super();
}
public Stack_used(Stack<Integer> stack){
this();
this.stack = stack;
}
public void pushOne(int n){
synchronized(this){
if(stack.size() >= Stack_used.SIZE){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Produce:"+stack.push(n));
// ,
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
}
public void popOne(){
synchronized(this){
if(stack.isEmpty()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("--Consume:"+stack.pop());
// ,
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
}
}
//
package test_produce;
import java.util.Stack;
public class Test {
public static void main(String[] args) {
Stack_used su = new Stack_used(new Stack<Integer>());
Produce produce = new Produce(su);
Consume consume = new Consume(su);
new Thread(produce).start();
new Thread(consume).start();
}
}
/*
// ...
Produce:0
Produce:1
Produce:2
Produce:3
Produce:4
--Consume:4
Produce:5
--Consume:5
--Consume:3
--Consume:2
--Consume:1
--Consume:0
Produce:6
Produce:7
Produce:8
Produce:9
--Consume:9
--Consume:8
--Consume:7
Produce:10
Produce:11
Produce:12
Produce:13
--Consume:13
--Consume:12
--Consume:11
--Consume:10
Produce:14
Produce:15
Produce:16
Produce:17
--Consume:17
--Consume:16
--Consume:15
--Consume:14
--Consume:6
Produce:18
Produce:19
--Consume:19
--Consume:18
...
*/