There is a problem with Java multi-threaded shared variables.

Asked 1 years ago, Updated 1 years ago, 105 views

I'm writing multi-threading the enemy's actions as I make the Java console game.

Make the thread a separate class and start() from the main.

The structure in the thread is rotated by a repeating door so that the enemy's physical strength is below zero.

But since it's multi-threaded, it keeps spinning even if the enemy's stamina is below zero.

First, by looking at the output values before and after the thread, we checked whether the enemy's physical strength was below zero There was nothing wrong with this.

And when I turned it to a single thread, I checked that the movement stopped.

So when I looked it up, they asked me to synchronize the run() method if I shared the thread and approached it.

Even though I put it on, only one thread is interrupted, and one continues.

What should I do in this case?

Isn't synchronization the answer?

If you tell me how to do it, I wanted to do it by myself, so I only uploaded it with the mouth coding.

Thank you for reading.

multithreading shared-variable

2022-09-22 20:24

1 Answers

The code that checks or changes the value of the shared variable must be changed to Critical Section.

In short, Critical Section refers to a section that allows limited access. This is usually used to make only one thread accessible.

public class Shared {
    private static shared instance = new Shared(); // an instance of a single tone pattern

    public static Shared getInstance() { return instance; }

    private int count;

    Private Shared() {} // As a private constructor to make it single tone.

    public int getCount() { return count; }
    public void setCount(int count) { this.count = count; }
    public int increment() { return ++count; }
    public int decrement() { return --count; }
    public int increment(int x) { return (count+=x); }
    public int decrement(int x) { return (count-=x); }
}

To simplify the example of sharing, a class of single-tone patterns was used as an example. If multiple threads share an instance of Shared above (Shared.getInstance()), changes in the value of count may not be synchronized between threads.

A simple solution is to add synchronized as follows:

public synchronized int getCount() ...;
public synchronized void setCount(int count) ...;

Alternatively, you can use RerentLock in the java.util.concurrent package.

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // rock settings. -- will replace the keyword synchronized

   public void m() {
     Lock lock () ; // critical the beginning of a section.
     try {
       Section code. // critical
     } finally {
       Section off unlock () ; // critical lock.
     }
   }
 }


2022-09-22 20:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.