자바의 쓰레드를 사용해서 자판기를 예제로 사용하였음..
import java.util.Stack;
class Producer implements Runnable{
private AutoMachine machine;
Producer(AutoMachine machine){
this.machine = machine;
}
public void run(){
for(int i = 0; i<10; i++){
machine.putDrink("음료수 " + i);
System.out.println("Producer : 음료수"+ i);
try{
Thread.sleep(500);
}
catch(Exception err){}
}
}
}
class Consumer implements Runnable{
private AutoMachine machine;
Consumer(AutoMachine machine){
this.machine = machine;
}
public void run(){
for(int i=0; i<10; i++){
System.out.println("Consumer: " + machine.getDrink());
try{
Thread.sleep(500);
}
catch(Exception err){}
}
}
}
class AutoMachine{
Stack store = new Stack();
public synchronized String getDrink(){
while(store.isEmpty()){
try{
this.wait();
}
catch(InterruptedException err){}
}
return store.pop().toString();
}
public synchronized void putDrink(String drink){
this.notify();
store.push(drink);
}
}
public class ThreadTest2 {
public static void main(String[] args) {
AutoMachine drink = new AutoMachine();
Producer pro = new Producer(drink);
Consumer con = new Consumer(drink);
Thread prot = new Thread(pro);
Thread cont = new Thread(con);
prot.start();
cont.start();
}
}
ChatGPT, 블록체인, 자바, 맥북, 인터넷, 컴퓨터 정보를 공유합니다.
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!