#Multi-Threading Needed :3
1 messages ยท Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
Here is an AI assisted attempt to answer your question ๐ค. Maybe it helps! In any case, a human is on the way ๐. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
cards. I need to implement multi-threading in my game to handle the following tasks concurrently:
-
Distributing the cards: Each player should receive their cards from their respective deck. This task can be done concurrently for all players.
-
Playing the game: Each player should be able to play their turn simultaneously. This includes choosing a card to play and updating the game state accordingly.
-
Checking for a winner: After each turn, the game should check if any player has won by having all four cards of the same rank.
To implement multi-threading in your game, you can use Java's ExecutorService and Callable interface. Here's a possible approach:
-
Create a class
Playerthat implements theCallableinterface. Thecall()method will handle distributing cards and playing turns for each player. -
In your main class, create an instance of
ExecutorServiceusingExecutors.newFixedThreadPool(numOfPlayers). This will create a thread pool with a fixed number of threads equal to the number of players.
-
Create a list of
Playerobjects, one for each player in your game. -
Submit all players to the thread pool using
executorService.submit(player). This will start executing each player's task concurrently. -
Implement the logic for distributing cards inside the
call()method of thePlayerclass. You can use synchronization mechanisms like locks or semaphores to ensure that each player receives their cards from their respective deck without conflicts. -
Implement the logic for playing turns inside the
call()method as well. Each player should choose a card to play and update the game state accordingly using synchronization mechanisms if necessary. -
After each turn, check if any player has won by having all four cards of the same rank.
-
Once all players have finished playing their turns, call
executorService.shutdown()to gracefully shut down the thread pool.
By implementing multi-threading in your game, you can distribute cards, play turns, and check for a winner concurrently, making the game more efficient and responsive.
I guess start with ChatGPTs suggestion?
imma be real with you, i have
not helpful tbh
i implemented some of the changes but the issue still was there
show your code please
ignore the deck and input validtor, threads started in cardGame.java and the discard and draw methods are in player
I uploaded your attachments as Gist.
im really not sure what im missing tbh, i added synchronized to both draw and discard so im confused why its not working. I didnt output that "notify player x that player y has won "
next line
"play x exit" but i doubt its helpful
@next jay so first off, why are Deck and CardGame Threads ?
because its a im starting the threads in cardGame
oh
yet they extend Thread
yeah but i need to synchronize the add and discard functions in deck
is that the problem?
i assumed i had to synchronize addcard() and removecard() in deck
I am struggling to see how is this game supposed to work
oh
so what are the rules ?
basically, player form a ring topology right , every player will draw from their left deck to their hand.
and discard from their hadn to their right deck when its not a preffered card number (player 1 wants card1's , player 2 will want card 2's)
each player is inbetween 2 decks
๐ค
ah
is it turn based ?
it's yes or no
no
so from what I understand
a player will draw from left deck
and put on right deck
then do it again
not they will put it in his hand
and when they have a card that isnt what they want, its discarded to deck on the right
and how many times do they do that ?
until winner
can a player draw a card from left deck, put it on right deck, then do that 10 times before the left player has time to do it once ?
nope , left deck -> **hand **, then **hand **-> *right hand *only
?
pretty sure you didn't want to write that
wdym i did
draw from left deck to players hand , discard a card from hand to right deck
yes
but I am asking
can you do that 10 times while another player did it only once ?
nope
so it's turn based ?
then using threads don't make any sense
how so?
because the point of threads is to do that, a player may do whatever it wants independently from other players
also
I wont fix the threads since well, you will delete them anyway
but I'll fix the rest
hmm
which version of java are you using ?
and is this an assignment ?
@next jay
hi no its okay bro , i really appreciate the help but i was just stuck on the threading part 
stream.forEach(line ->{
Card card = new Card(Integer.parseInt(line));
pack.add(card);
});
This is a bad use of a stream, you should do
pack.addAll(stream.map(line -> new Card(Integer.parseInt(line)).toList());
actually
this whole loop can be simplified
how so>
like you are reading the file twice for no reason
not only that
but the first time, you are using a good approach of Files.lines, but the second time you are manually reading it with a BufferedReader ???
yeah i need to change a bunch of stuff lmao
Also, don't hide exceptions
and don't catch it just because java told you to
there is a reason for why java asks you this
it's not just catching for the sake of catching
if the exception is fatal ie the program cannot work if it happens, then you should rethrow it as an unchecked exception
good pointtt
im a little baby right now
but one day
ill make it
public void initualiseFile(){
File file = new File(fileName);
try{
file.createNewFile();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//Clears contents of file
try{
FileWriter writer = new FileWriter(fileName);
BufferedWriter buffwriter= new BufferedWriter(writer);
buffwriter.write("");
buffwriter.close();
}catch(IOException e){
e.printStackTrace();
}
}
Like this one, if you get an exception here, pretty sure the only option is to crash
speaking of this
please don't use File
use Files and Path, you used it above, so you should know it
and
you just used Files and Path
why are you using FileWrriter ???
and you just used a try-with-resources above, why are you then using a regular try + manually closing ? you are not even closing correctly, there is a leak
same for all the other place without a try-with-resources
ah i did not know that
you didn't know what ?
also
Don't create a random each time
it's not really random then
okay
and you are abusing syncronized and notify, no way it would work, but since you will get rid of the thread, then you will get rid of that anyway
and, also
don't write to a file at each turn
I mean
why can't you write when it's over ?
and a method called result() should write to a file
and don't omit @Override when you override
okay sir
private static int numOfPlayers;
//private static String filePath;
public InputPackValidator(int numOfPlayers/* , String filepath*/){
this.numOfPlayers=numOfPlayers;
//this.filePath=filepath;
}
shouldn't be static
just private?
cause of this
String str="";
for(Card card : deckContents){
str=str+Integer.toString(card.getValue())+" ";
}
return str;
use a StringBuilder, StringJoiner or Stream here
will do
?
for(Player player : playerList){
player.initualHand();
if (player.isWinningHand()){
System.out.println("Game Over");
player.result();
break;
}
// Threads started //
player.start();
}
Also, how is the game supposed to be over before it even started ?
i think that's all