Where is a problem with this multithreading code? - java

I want to calculate sum of 2D array with multithreading. But I can't get correct result and programm can't end for some reason.
MatrixService devides task to threads and contains result. (methods getSumma() and setSumma(int summa) are taken from Herbert Schildt)
public class MatrixService {
private boolean valueGet = false;
private int summa;
public int sum(int[][] matrix, int nThreads) {
for (int i = 0; i < nThreads; i++) {
new ColumnSummator(this, matrix, nThreads, i);
}
return summa;
}
public synchronized int getSumma() {
while (valueGet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
valueGet = true;
notify();
return summa;
}
public synchronized void setSumma(int summa) {
while (!valueGet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
this.summa = summa;
valueGet = false;
notify();
}
}
ColumnSummator choose columns for sum which this Thread should calculate
import java.util.ArrayList;
import java.util.List;
public class ColumnSummator implements Runnable {
private int summOfColumns;
private final MatrixService matrixService;
private final int[][] matrix;
private final List<Integer> numberColumnsForCount = new ArrayList<>();
public ColumnSummator(MatrixService matrixService, int[][] matrix, int nThreads, int columnSummatorId) {
this.matrixService = matrixService;
this.matrix = matrix;
for (int i = 0; i < matrix[0].length; i++) {
if (i % nThreads == columnSummatorId) {
numberColumnsForCount.add(i);
}
}
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < matrix[0].length; i++) {
if (numberColumnsForCount.contains(i)) {
for (int j = 0; j < matrix.length; j++) {
summOfColumns += matrix[j][i];
}
}
}
matrixService.setSumma(matrixService.getSumma() + summOfColumns);
}
}
And inside main:
public static void main(String[] args) {
MatrixService matrixService = new MatrixService();
int[][] matrix = new int[10][10];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = (i + 1) * (j + 1);
}
}
int summa = matrixService.sum(matrix, 6);
System.out.println(summa);
}

Related

Java - Strange concurrent problems about ReentrantLock

I have 2 test cases, while the first one is failed and the second one can successed.
The only difference code is method incr of class Incr.
Why?
public class ReentrantSpinLockTest {
private final Incr incr = new Incr();
#Test
public void lock() throws InterruptedException {
int n = 50;
int inner_loop = 100_000;
CountDownLatch boot = new CountDownLatch(n);
CountDownLatch complete = new CountDownLatch(n);
for (int i = 0; i < n; ++i) {
new Thread(() -> {
try {
boot.await();
for (int k = 0; k < inner_loop; ++k) {
incr.incr();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
complete.countDown();
}
}).start();
boot.countDown();
}
complete.await();
int expect = n * inner_loop;
int actual = incr.getI();
assert expect == actual : String.format("expect %d actual %d", expect, actual);
}
}
The successful Incr:
public class Incr {
private final ReentrantLock lock = new ReentrantLock();
private volatile int i;
// only this diff
public void incr() {
lock.lock();
lock.lock();
i++;
lock.unlock();
lock.unlock();
}
public int getI() {
return i;
}
}
The failed Incr:
public class Incr {
private final ReentrantLock lock = new ReentrantLock();
private volatile int i;
public void incr() {
int k = Math.abs(new Random().nextInt() % 5);
for (int t = 0; t < k; ++t) {
lock.lock();
}
i++;
for (int t = 0; t < k; ++t) {
lock.unlock();
}
}
public int getI() {
return i;
}
}

New to Programming (Java) - dont know how to fix an error with a small Console Game simular to Snake

I just started to learn Java and am working on a small project which is supposed to create a gameField in a 2 dimensional String Array Field Borders are marked with a "#". In this Field I want to spawn a player who is marked as ">". This player can then turn left or right (∧ for looking up for example) and then has the option to move forward one space.
I currently have the gameField created and now want to spawn the player into that 2 dimensional String Array for which I have made a spawnPlayer method/function in the class Player. I now want to add / open that method/function in the main method. This is where I am getting the error messages and dont know what to do.
public class KonsolenWanderer {
public static void main(String[] args) {
Field field1 = new Field();
field1.createField();
Player player1 = new Player();
//Error is here!!!
player1.spawnPlayer();
}
}
public class Field {
private String [][] fieldSize = new String [10][10];
public void createField() {
for(int i = 0; i < fieldSize.length; i++) {
for(int j = 0; j < fieldSize[i].length; j++) {
//Creating Field Border
if(i == 0 || i == 9 || j == 0 || j == 9) {
fieldSize[i][j] = "#";
}
else {
fieldSize[i][j] = " ";
}
System.out.print(fieldSize[i][j]);
}
System.out.println();
}
}
public String[][] getFieldSize() {
return fieldSize;
}
public void setFieldSize(String[][] fieldSize) {
this.fieldSize = fieldSize;
}
}
public class Player {
private static int xPosition;
private static int yPosition;
private String up = "∧";
private String down = "∨";
private String left = "<";
private String right = ">";
private String currentDirection;
Player() {
xPosition = 4;
yPosition = 4;
}
public void spawnPlayer(String[][]fieldSize) {
fieldSize[xPosition][yPosition] = ">";
}
public static void moveForward() {
}
public static void turnPlayerLeft() {
}
public static void turnPlayerRight() {
}
}
You need to set the position inside the field object or expose fieldSize from within Field class.
public class KonsolenWanderer {
public static void main(String[] args) {
Field field = new Field();
field.createField();
Player player1 = new Player();
//Error is here!!!
player1.spawnPlayer(new String[8][8], field);
field.showField();
}
}
class Field {
private String [][] fieldSize = new String [10][10];
public void createField() {
for(int i = 0; i < fieldSize.length; i++) {
for(int j = 0; j < fieldSize[i].length; j++) {
//Creating Field Border
if(i == 0 || i == 9 || j == 0 || j == 9) {
fieldSize[i][j] = "#";
}
else {
fieldSize[i][j] = " ";
}
System.out.print(fieldSize[i][j]);
}
System.out.println();
}
}
public void showField() {
for(int i = 0; i < fieldSize.length; i++) {
for(int j = 0; j < fieldSize[i].length; j++) {
System.out.print(fieldSize[i][j]);
}
System.out.println();
}
}
public String[][] getFieldSize() {
return fieldSize;
}
public void setFieldSize(String[][] fieldSize) {
this.fieldSize = fieldSize;
}
public void setPlayerPosition(int i, int j) {
i++;
j++;
fieldSize[i][j] = ">";
}
}
class Player {
private static int xPosition;
private static int yPosition;
private String up = "∧";
private String down = "∨";
private String left = "<";
private String right = ">";
private String currentDirection;
Player() {
xPosition = 4;
yPosition = 4;
}
public void spawnPlayer(String[][] fieldSize, Field field) {
for(int i = 0; i < fieldSize.length; i++) {
if (i == fieldSize.length -1){
for(int j = 0; j < fieldSize[i].length; j++) {
if (j == fieldSize.length - 1 )
field.setPlayerPosition(i, j);
}
}
}
}
public static void moveForward() {
}
public static void turnPlayerLeft() {
}
public static void turnPlayerRight() {
}
}

Unexpected error with my class

When writing a class it is giving me an expected token error and I can not figure out how to solve it or why it is giving it to me.
Here's the code:
public class SetUpDoors {
private int DoorAmount;
private int WinningDoorAmount;
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
void setDoorAmount(int userDoors){
DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
WinningDoorAmount = userWinningDoors;
}
}
it is giving the error on the ; at the end of private int winnerSelect = 0;
and an error for the } right below DoorAmount--;
The first is expected token "{" and the second is add "}" to complete block.
You must declare following code inside a method.
For example:
public void newMethod(){
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
try this
public class SetUpDoors {
private int DoorAmount;
private int WinningDoorAmount;
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;
{
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
}
void setDoorAmount(int userDoors){
DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
WinningDoorAmount = userWinningDoors;
}
}

Repaint() method causes UI to flash and flicker

So I have been coding this little UI for a while and for some reason the repaint() method seems to cause the image generated on the screen to flicker and flash. Is there a way to prevent this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.Timer;
public class userInterfaceSimple extends JFrame implements ActionListener
{
static ArrayList<Creature> list = new ArrayList<Creature>();
static JButton next = new JButton("Begin");
static Timer timer = new Timer();
static JFrame frame = new JFrame();
final static JPanel pane = new JPanel();
public static void main(String[] args)
{
new userInterfaceSimple();
}
public userInterfaceSimple()
{
super("Toy Planet: Life, a Simulation");
setSize(1000,1000);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(pane, BorderLayout.CENTER);
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(next.getText().equals("Begin"))
{
next.setText("Stop");
timer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run()
{
checkRules();
repaint();
}
}, 250, 250);
}
else
{
next.setText("Begin");
timer.cancel();
timer = new Timer();
}
}
});
add(next, BorderLayout.SOUTH);
for(int j = 0; j < 3; j ++)
{
Creature orgArc = new Creature();
for(int i = 0; i < 20; i++)
{
list.add(new Creature(orgArc.gene));
}
}
sortList();
}
public void paint(Graphics g)
{
super.paint(g);
for(int i = 0; i < list.size(); i++)
{
g.setColor(list.get(i).getColor());
int size = list.get(i).getSize();
g.fillOval(list.get(i).getX() - size/2, list.get(i).getY() - size/2,size,size);
}
}
public static void checkRules()
{
int size = list.size();
for(int i = 0; i < size; i++)
{
try
{
for(int j = 0; j < size; j++)
{
boolean alreadyMoved = false;
if(!(list.get(i)).equals(list.get(j)))
{
int x = list.get(j).getX() - (list.get(i)).getX();
int y = list.get(j).getY() - (list.get(i)).getY();
double z = Math.sqrt(x*x + y*y);
//Passive Interaction Rules
//Sight Check
if(list.get(j).getSense() > z)
{
list.get(j).moveTo(list.get(i));
alreadyMoved = true;
}
if(z <= 1.5)
{
//Active Interaction Rules
//Breeding Check
if(list.get(j).isCompatible(list.get(i)))
{
list.add(list.get(j).breed(list.get(i)));
sortList();
}
//Eating Check
else if(list.get(j).getAggro() > 15 || list.get(j).getDiet() > 3)
{
list.get(j).eat(list.get(i));
}
}
}
//If no checks fire then move randomly
if(alreadyMoved == false)
{
Organism temp = new Organism();
list.get(j).moveTo(temp);
}
}
//Hunger Check
list.get(i).hungerCheck();
}
catch(Exception e)
{
}
list.get(i).validate();
size = size - validateList();
}
/*for(int i = 0; i < list.size(); i ++) //for debugging.
{
System.out.println(list.get(i).getInfo());
}
System.out.println("----");*/
}
public static int getClosestCreature(Organism org)
{
int x,y;
double z;
double tempZ = 100000;
int closest = 0;
for(int i = 0; i < list.size(); i++)
{
if(!(list.get(i)).equals(org))
{
x = org.getX() - (list.get(i)).getX();
y = org.getY() - (list.get(i)).getY();
z = Math.sqrt(x*x + y*y);
if(z < tempZ)
{
closest = i;
tempZ = z;
}
}
}
return (closest);
}
public static int validateList()
{
int netLoss = 0;
for(int i = 0; i < list.size(); i++)
{
if((list.get(i)).getAlive() == false)
{
list.remove(i);
netLoss = netLoss + 1;
}
}
return netLoss;
}
public static void sortList()
{
Creature temp;
for(int i = 0; i < list.size(); i ++)
{
for(int j = 1; j < list.size() - i; j++)
{
if(list.get(j - 1).getSpeed() > list.get(j).getSpeed())
{
temp = list.get(j - 1);
list.set(j - 1, list.get(j));
list.set(j, temp);
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Thanks for you help!
Yes, it is simple: Double Buffering should fix it. For more reference, visit http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html
First you should create private BufferedImage bufferImage;
In your public void paint(Graphics g) you should paint stuff into this bufferImage, and then, when bufferImage is filled, paint it g.drawImage(bufferImage, 0, 0, null);
public void paint(Graphics g) {
Graphics2D gr = bufferImage.createGraphics();
for(int i = 0; i < list.size(); i++)
{
gr.setColor(list.get(i).getColor());
int size = list.get(i).getSize();
gr.fillOval(list.get(i).getX() - size/2, list.get(i).getY() - size/2,size,size);
}
super(g);
g.drawImage(bufferImage, 0, 0, null);
}
Not compiled, but something like this should work.

"A Java Exception has occurred"

So I'm trying to run my pacman project as a jar(also tried runnable) and I just get the error message you see in the title. It runs perfectly fine in eclipse/netbeans, but whilst cleaning/building i see the warnings:
Note: C:\Users\Lucas\Documents\Eclipse\PackMan\src\game\packman\GameData.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The main class is correct and assigned. Does anybody know what I'm doing wrong?
Here is my GameData class
public class GameData {
int mazeNo;
CopyOnWriteArrayList<Position> pills;
CopyOnWriteArrayList<Position> powerPills;
public MoverInfo packman;
public GhostInfo[] ghostInfos = new GhostInfo[4];
public int score;
Maze[] mazes;
boolean dead = false;
boolean win = false;
public GameData() {
mazes = new Maze[4];
// load mazes information
for (int m=0; m<4; m++) {
mazes[m] = new Maze(m);
}
setMaze(mazeNo);
}
private void setMaze(int m) {
packman = new MoverInfo(mazes[m].packmanPos);
for (int g=0; g<4; g++) {
ghostInfos[g] = new GhostInfo(mazes[m].ghostPos);
}
pills = new CopyOnWriteArrayList((List<Position>)(mazes[m].pills.clone()));
powerPills = new CopyOnWriteArrayList((List<Position>)(mazes[m].powerPills.clone()));
}
public void movePackMan(int reqDir) {
if (move(reqDir, packman)) {
packman.curDir = reqDir;
} else {
move(packman.curDir, packman);
}
}
private int wrap(int value, int incre, int max) {
return (value+max+incre)%max;
}
private boolean move(int reqDir, MoverInfo info) {
// current position of packman is (row, column)
int row = info.pos.row;
int column = info.pos.column;
int rows = mazes[mazeNo].rows;
int columns = mazes[mazeNo].columns;
int nrow = wrap(row, MoverInfo.DROW[reqDir], rows);
int ncol = wrap(column, MoverInfo.DCOL[reqDir], columns);
if (mazes[mazeNo].charAt(nrow, ncol) != '0') {
info.pos.row = nrow;
info.pos.column = ncol;
return true;
}
return false;
}
public void update() {
if (pills.contains(packman.pos)) {
pills.remove(packman.pos);
score += 5;
} else if (powerPills.contains(packman.pos)) {
powerPills.remove(packman.pos);
score += 50;
for (GhostInfo g:ghostInfos) {
g.edibleCountDown = 500;
}
}
for (GhostInfo g:ghostInfos) {
if (g.edibleCountDown > 0) {
if (touching(g.pos, packman.pos)) {
// eat the ghost and reset
score += 100;
g.curDir = g.reqDir = MoverInfo.LEFT;
g.pos.row = mazes[mazeNo].ghostPos.row;
g.pos.column = mazes[mazeNo].ghostPos.column;
g.edibleCountDown = 0;
}
g.edibleCountDown--;
} else {
if (touching(g.pos, packman.pos)) {
dead = true;
}
}
}
// level is cleared
if (pills.isEmpty() && powerPills.isEmpty()) {
mazeNo++;
if (mazeNo < 4) {
setMaze(mazeNo);
} else if (mazeNo == 5) {
win = true;
} else {
// game over
dead = true;
}
}
}
private boolean touching(Position a, Position b) {
return Math.abs(a.row-b.row) + Math.abs(a.column-b.column) < 3;
}
public void moveGhosts(int[] reqDirs) {
for (int i=0; i<4; i++) {
GhostInfo info = ghostInfos[i];
info.reqDir = reqDirs[i];
if (move(info.reqDir, info)) {
info.curDir = info.reqDir;
} else {
move(info.curDir, info);
}
}
}
public int getWidth() {
return mazes[mazeNo].width;
}
public int getHeight() {
return mazes[mazeNo].height;
}
public List<Integer> getPossibleDirs(Position pos) {
List<Integer> list = new ArrayList<>();
for (int d=0; d<4;d++) {
Position npos = getNextPositionInDir(pos, d);
if (mazes[mazeNo].charAt(npos.row, npos.column) != '0') {
list.add(d);
}
}
return list;
}
private Position getNextPositionInDir(Position pos, int d) {
int nrow = wrap(pos.row, MoverInfo.DROW[d], mazes[mazeNo].rows);
int ncol = wrap(pos.column, MoverInfo.DCOL[d], mazes[mazeNo].columns);
return new Position(nrow, ncol);
}
}

Categories

Resources