问题描述
我从教授那里得到了与生产者-消费者问题相关的任务。 任务是实现生产者-消费者过程,但是
--
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
public class Threadexample {
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 {
pc.produce();
}
catch (InterruptedException e) {
e.printstacktrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
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 = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
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
{
while (true) {
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);
}
}
}
}
}
输出:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
我不确定我是否完全理解我的任务。是否可以在此代码上实现给定的任务?我希望你给我一些建议或任何来源,这样我才能明白该怎么做。 先谢谢大家!
解决方法
如果我从您的描述中正确理解了您的问题,您应该从两个线程更改该字段的值。您想创建一个类级字段和两个同步方法来更改他的值,然后创建两个线程并从它们交替调用两个操作。我想你可以这样写:
public class Solution0 {
private volatile int count;
public synchronized void increment() throws InterruptedException {
count = count + 5;
Thread.sleep(1000);
notifyAll();
wait();
}
public synchronized void divide() throws InterruptedException {
count = count / 2;
Thread.sleep(1000);
notifyAll();
wait();
}
public static void main(String[] args) {
Solution0 solution = new Solution0();
Thread t1 = new Thread(() -> {
try {
while (true){
solution.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
while (true){
solution.divide();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
}
}
此外,如果您需要实数,您可以将字段 count
的类型从 int
更改为 double
。