私はJavaの同期とスレッド間の通信を理解するためにPCの問題に取り組んできました。一番下にあるコードを使用して、出力がJava同期を使用してプロデューサ/コンシューマを理解する
Producer produced-0
Producer produced-1
Producer produced-2
Consumer consumed-0
Consumer consumed-1
Consumer consumed-2
Producer produced-3
Producer produced-4
Producer produced-5
Consumer consumed-3
Consumer consumed-4
だったが、出力は私の理解は、消費者が通知されているので、私はこのような出力を期待
Producer produced-0
Consumer consumed-0
Producer produced-1
Consumer consumed-1
Producer produced-2
Consumer consumed-2
Producer produced-3
として以下のようなものであってはなりませんメソッドが終了すると、プロダクションメソッドがロックを解除するとすぐに生成された値。その結果、待機していた消費者ブロックは、生成された値を消費するために同期状態取得ロックに入り、一方、プロデューサメソッドはブロックされる。このロックは、同期のためにブロックされたプロデューサスレッドによって獲得された消費メソッドの最後に解放され、ロックは取得されたために各メソッドがブロックされるとサイクルが継続する。
私は何を誤解したか教えてください。通知& &のThread.sleep
Object.notify():2 mothodsのおかげ
package MultiThreading;
//Java program to implement solution of producer
//consumer problem.
import java.util.LinkedList;
public class PCExample2
{
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
while (true) {
pc.produce();
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
while (true) {
pc.consume();
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumber (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 12;
int value = 0;
// Function called by producer thread
public void produce() throws InterruptedException
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();
//to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
https://stackoverflow.com/questions/2332537/producer-consumer-threads-using-a-queue/37767243#37767243 –
これらのスレッドを移動するとどうなるかを知りたいかもしれません。 sleep(1000) 'は' synchronized'ブロックを呼び出します。 –