简体   繁体   English

螺纹评分系统

[英]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. 我有一个计分系统,旨在将一个点添加到临时的addpoints变量中,以向玩家显示他们最近获得了多少点。 Then after about 1 second the added points should be added to the players score. 然后大约1秒钟后,应将增加的分数添加到玩家分数中。

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. 首先,它仅允许我为每个线程增加1点,这远非理想。 Second it doesn't actually work. 其次,它实际上不起作用。 Neither addedPoints nor score is updated. addpoints和score均不会更新。 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: 在一次添加多个点而不是一次添加多个点方面,可以使用ParameterizedThreadStart代替:

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). 如果要缓慢消耗这些点,请将这些点传递给线程(请参见如何将参数传递给Java Thread? ),然后使用while循环消耗所有点(假设将传递的参数存储为点)。 。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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