gpt4 book ai didi

Java并行同步2个线程

转载 作者:行者123 更新时间:2023-12-02 04:05:38 24 4
gpt4 key购买 nike

-----------------已解决,谢谢您的建议! ------------

我有以下代码,其中有一个数字数组。我想创建两个并行执行的线程。第一个线程打印数值,第二个线程相乘。这是我的代码

class Synchronize {

private boolean writeable = true;

public synchronized void numbers() {
{
while (!writeable) {
try {
wait();
} catch (InterruptedException e) {
}
}
writeable = false;
notify();
}
}

public synchronized void multiply() {
while (writeable) {
try {
wait();
} catch (InterruptedException e) {
}
}
writeable = true;
notify();
}
}

class Numbers
extends Thread {

private Synchronize s;
int numbers = 0;
int[] array;

Numbers(String name, Synchronize s, int[] array) {
super(name);
this.s = s;
this.array = array;
}

public void run() {
try {
for (int i = 0; i <= array.length - 1; i++) {
System.out.print("\nIn " + getName() + " number is " + array[i] + "\t");
Thread.sleep(1000);
s.numbers();
}
} catch (Exception e) {
}
}
}


class Multiply
extends Thread {

private Synchronize s;
int multiply = 1;
int[] array;

Multiply(String name, Synchronize s, int array[]) {
super(name);
this.s = s;
this.array = array;
}

public void run() {
try {
for (int i = 0; i <= array.length - 1; i++) {
multiply = multiply * array[i];
System.out.print("\nIn " + getName() + " multiply is " + multiply + "\t");
Thread.sleep(1000);
s.multiply();
}
} catch (Exception e) {
}
}
}


public class NewThread {

public static void main(String[] args) {

int array[] = {
1,
4,
5,
2,
7,
8,
9
};

Synchronize s = new Synchronize();
new Numbers("Thread #1 ", s, array).start();
new Multiply("Thread #2 ", s, array).start();
}
}

代码输出如下:

In Thread #1  number is 1   
In Thread #2 multiply is 1
In Thread #1 number is 4
In Thread #2 multiply is 4
In Thread #2 multiply is 20
In Thread #1 number is 5
In Thread #1 number is 2
In Thread #2 multiply is 40
In Thread #1 number is 7
In Thread #1 number is 8
In Thread #2 multiply is 280
In Thread #2 multiply is 2240
In Thread #1 number is 9
In Thread #2 multiply is 20160

我想要怎样

In Thread #1  number is 1   
In Thread #2 multiply is 1
In Thread #1 number is 4
In Thread #2 multiply is 4
In Thread #1 number is 5
In Thread #2 multiply is 20
In Thread #1 number is 2
In Thread #2 multiply is 40
In Thread #1 number is 7
In Thread #2 multiply is 280
In Thread #1 number is 8
In Thread #2 multiply is 2240
In Thread #1 number is 9
In Thread #2 multiply is 20160

我不想要带有队列的方法...如果有人知道该怎么做,我只想修改此代码。

最佳答案

问题是 System.out.println() 位于同步块(synchronized block)之外,因此尽管评估已正确序列化,但打印结果可能会交换顺序。

您可以做的是将 System.out.println() 包装到 Runnable 中,将其传递给 numbers(Runnable Printer)multiply(Runnable Printer) 并从同步方法中调用 printer.run()

关于Java并行同步2个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com