/* 제작자 만 실행하고 소비자가 아무것도 소비하지 않을 때마다 여기에서 무엇이 잘못 되었습니까? 이 코드에서 무엇이 잘못되었는지 설명해주십시오. Java : 멀티 스레딩
내 예상 결과
: 생산자 제작 한 항목은 다음 소비자가 해당 항목 *을 소비하는 당신이 sycnhronize 기다려 그렇지 객체 프로듀서를 들어, 사용 목록을 통지 할 필요가 모든/import java.util.ArrayList;
public class ConsumerAndProducerMain
{
public static void main(String[] args) throws InterruptedException
{
int MAX_SIZE = 10;
ArrayList<Integer> list = new ArrayList<Integer>(10);
final Producer producer = new Producer(MAX_SIZE, list);
final Consumer consumer = new Consumer(MAX_SIZE, list);
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
producer.producer();
}
catch (InterruptedException e)
{
System.out.println("Producer : Exception occured because of multi threading...");
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
consumer.consumer();
}
catch (InterruptedException e)
{
System.out.println("Consumer : Exception occured because of multi threading...");
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Program terminated..");
}
}
class Producer {
int size;
ArrayList<Integer> list;
public Producer(int size, ArrayList<Integer> list)
{
this.size = size;
this.list = list;
}
public void producer() throws InterruptedException{
int value = 0;
while(true){
synchronized (this)
{
if(list.size() == size){
System.out.println("Producer : List is full");
wait();
}else{
list.add(++value);
Thread.sleep(200);
notify();
System.out.println("Value produce by the producer : "+value);
}
}
}
}
}
class Consumer {
int size;
ArrayList<Integer> list;
public Consumer(int size, ArrayList<Integer> list)
{
this.size = size;
this.list = list;
}
public void consumer() throws InterruptedException{
while(true){
synchronized (this)
{
if(list.isEmpty()){
System.out.println("Consumer : List is empty");
wait();
}else{
int removedItem = list.remove(list.size());
Thread.sleep(5000);
notify();
System.out.println("Value consumed by the consumer : "+removedItem);
}
}
}
}
}
이는 Java 동시성에 대한 소개 자료를 읽음으로써 해결되어야합니다. 각 스레드는 자체 잠금을 사용하므로 조정이 발생하지 않습니다. –
Marko가 만들고있는 요지는 '대기'하기 위해'notify '가 작동하기 위해서, 그들은 같은 객체를 알리거나 대기해야한다는 것입니다. 그러나 각 객체는 공통 객체 대신 자체적으로 잠그고 있습니다. –
유사 [동일한 스레드가 두 개의 동기화 된 메소드를 동일한 객체에서 실행할 수 있음] (http://stackoverflow.com/questions/26361367/same-thread-isable-to-execute-on-same-objects-two -synchronized-methods/26362523 # 26362523) – OO7