Question: JAVA The quarry-collecting problem in a multi-player game can be stated as follows: A shared quarry can be concurrently collected by any number of players,

JAVA

The quarry-collecting problem in a multi-player game can be stated as follows: A shared quarry can be concurrently collected by any number of players, but when a player get certain amount of quarry and must update the amount of quarry, it must have exclusive access. Write a program for the quarry-collecting problem. Test that three players collect quarry concurrently and your program functions. You may choose any programming language you are familiar with. Please submit your homework to the blackboard system, including every source file (e.g., programname1.java, programname2.cpp, or programname3.h)

Define a player

public class player extends Thread {

public void run(){

// your code here }

}

Define a quarry

public class quarry {

/ your class variable and methods here

// one way to make a method exclusive to only one thread is

// to use the reserved word synchronized

synchronized public void methodname(){ } }

Define a game to test three players

Public class game { Public static void main(String args[]){

Player player1 = new player();

// define more players player2, player3

// simulation player 1, player 2, player 3 running at the same time

player1.start();

// start more players } }

Source files:

Simplegame2.java

package game2;
public class simplegame2 { public static void main(String args[]){ player player1 = new player(); player player2 = new player(); System.out.println("synchronized total gold amount is " + RESOURCE.getGoldamount()); player1.start(); player2.start(); } }

player.java

package game2; public class player extends Thread { public void run(){ // please write your own version of code here for (int i=0; i <= 10; i++){ System.out.println(this.getName() + " is trying to get " + (i*10) + " gold ..."); RESOURCE.decreaseGoldamount(i*10); System.out.println("synchronized current gold left is " + RESOURCE.getGoldamount()); } } }

RESOURCE.java

package game2; public class RESOURCE { static int goldamount = 1100; public static int getGoldamount() { return goldamount; } public static void setGoldamount(int goldamount) { RESOURCE.goldamount = goldamount; } synchronized public static void decreaseGoldamount(int amount){ goldamount = goldamount - amount; } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!