简体   繁体   中英

Threaded Scoring System

I'm starting to learn threading and have encountered a problem.

I have a scoring system that is designed to add a point to a temporary addedPoints variable to show the player how many points they have recently earned. Then after about 1 second the added points should be added to the players score.

My attempt looks like this:

public static void AddPoints(int points)
{
    for (int i = 0; i < points; i++)
    {
        Thread addThread = new Thread(new ThreadStart(ThreadedPoint));
    }
}

private static void ThreadedPoint()
{
    addedPoints += 1;
    Thread.Sleep(1000);
    score += 1;
    addedPoints -= 1;
}

This has two problems. First it only allows me to add 1 point per thread which is far from ideal. Second it doesn't actually work. Neither addedPoints nor score is updated. How can I fix this?

You haven't actually started your thread so nothing will ever happen:

public static void AddPoints(int points)
{
    for (int i = 0; i < points; i++)
    {
        Thread addThread = new Thread(new ThreadStart(ThreadedPoint));
        addThread.Start();
    }
}

In terms of adding multiple points at once rather than one at a time you can use a ParameterizedThreadStart instead:

public static void AddPoints(int points)
{
   Thread addThread = new Thread(new ParameterizedThreadStart(ThreadedPoint));
   addThread.Start(points); //You may need a cast of points to Object here
}

private static void ThreadedPoint(Object data)
{
    int points = (int)data;
    addedPoints += points;
    Thread.Sleep(1000);
    score += points;
    addedPoints -= points;
}

Unless you want to learn threading you'd be better off redesigning the way your store "recently earned" in such a way that it does not required delayed update.

Ie update score immediately and have separate filed that says when latest points where earned, so you can always get score and with some code figure out "recently earned" info.If needed you can adjust display value of score by "recently earned".

If you want to consume the points slowly, pass the points to the thread (see How can I pass a parameter to a Java Thread? ) and use a while loop to consume all of the points (assuming you store the passed parameter as points).

while(points > 0) {
  points -=1;
  addedPoints += 1;
  Thread.Sleep(1000);
  score += 1;
  addedPoints -= 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM