Java中两个进程的生产者-消费者问题
我从我的教授那里得到了一个关于生产者和消费者问题的任务。 任务是实现生产者-消费者过程,但是Java中两个进程的生产者-消费者问题,java,operating-system,Java,Operating System,我从我的教授那里得到了一个关于生产者和消费者问题的任务。 任务是实现生产者-消费者过程,但是 第一个过程每次应增加其值5 第二个进程每次应将其值除以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();
}
}
此外,如果需要实数,您可以将字段的类型从
int
更改为double
。噢,非常感谢!我想这一个是正确的对不起,我应该独立运行这个文件还是实现第一个代码?这个例子有一个“main”方法,所以你可以从中创建jar归档文件,并通过“java-example.jar”运行它对不起,我问了一些愚蠢的问题,但是有可能在在线编译器中运行它吗?我试图创建jar归档,但出现了“无主清单atribute”和其他错误:c
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();
}
}