我正在尝试创建一个类来计算5种不同形状的总面积和周长,但是给定形状的每个区域和周长都是由一个单独的线程计算的。到目前为止,我无法正确地同步线程,因此可以正确计算totalArea和totalPerimeter。任何建议让线程工作?如果我不用线程计算每个形状,则下面代码的totalArea和totalPerimeter应该等于该区域的610.829和周长的187.115。如果我这样做,价值会变得完全随机。
package PartB;
import PartA.Step2.*;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Picture implements Runnable{
public List<Shape> picture;
public Shape selectedShape;
public ListIterator<Shape> e;
double totalArea;
double totalPerimeter;
double a;
double b;
double c;
double length;
double width;
double height;
double radius;
public Picture(double a, double b, double c, double length, double width, double height, double radius){
this.a = a;
this.b = b;
this.c = c;
this.length = length;
this.width = width;
this.radius = radius;
this.height = height;
Shape[] shapes = {new Circle(radius), new Square(length),
new Rectangle(length, width), new Parallelogram(length, width, height),
new Triangle(a, b, c)};
picture = new CopyOnWriteArrayList<>(Arrays.asList(shapes));
}
public double getTotalArea(){return totalArea;}
public double getTotalPerimeter(){return totalPerimeter;}
@Override
public void run() {
synchronized (this) {
totalArea += selectedShape.getArea();
totalPerimeter += selectedShape.getPerimeter();
System.out.println(totalArea);
System.out.println(totalPerimeter);
}
}
public static void main(String[] args){
Picture pictures = new Picture(5, 6, 7, 8, 9, 10, 11);
for(pictures.e = pictures.picture.listIterator(); pictures.e.hasNext();){
pictures.selectedShape = pictures.e.next();
new Thread(pictures).start();
}
}
}
形状界面:
package PartA.Step2;
public interface Shape {
double getPerimeter();
double getArea();
}
其中一个形状的子类:
package PartA.Step2;
public class Circle implements Shape, Cloneable {
double radius;
public Circle(double radius){
this.radius = radius;
}
@Override
public double getArea() {
CalculateShape calc = (radius)->Math.PI * Math.pow(radius[0], 2);
return calc.process(radius);
}
@Override
public double getPerimeter() {
CalculateShape calc = (radius)->2 * Math.PI * radius[0];
return calc.process(radius);
}
@Override
public String toString() {
return "Area: " + getArea() +
"\nPerimeter : " + getPerimeter();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Circle){
if(((Circle) obj).radius == radius)
return true;
}
return false;
}
}
答案 0 :(得分:0)
我忘了有一种方法可以让主线程等到线程不再存在。通过这样做,我能够使每个线程计算形状区域和周长而不受其他线程的干扰。 @cheiron说,同步部分毫无意义:
public static void main(String[] args){
Picture pictures = new Picture(5, 6, 7, 8, 9, 10, 11);
for(pictures.e = pictures.picture.listIterator(); pictures.e.hasNext();){
pictures.selectedShape = pictures.e.next();
Thread thread = new Thread(pictures);
thread.start();
while(thread.isAlive()){
try {
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
我现在可以获得整个图片的正确总面积和总周长。