2

因此,我希望一个线程不断更新您拥有多少“金币”,而另一个线程将运行游戏。

问题是每个光标都在更改,我首先通过让它们不同步和睡眠来修复它,但是当我希望用户输入文本时,它会转到第一行。有人知道怎么修这个东西吗?

import java.awt.*;
import java.lang.*;
import java.util.*;
import java.awt.Color;
import hsa.Console;


public class Money {
    public static long gold = 0;
    public static long rate = 1;
    public static void main(String args[]) {
        Console con = new Console (41, 100);
        ThreadTest test1 = new ThreadTest();
        ThreadTest2 test2 = new ThreadTest2();
        test1.setConsole(con);
        test2.setConsole(con);
        test1.start();
        test2.start();
    }
}

public class ThreadTest extends Thread {
    Console c; 
    public void setConsole(Console con) {
        c = con;
    }
    public void run() {
        try {
            sleep(900);
        } catch (InterruptedException e) {
        }
        c.println("Welcome to the world of grind\nThe goal of the game is to amass money and get stuff!\nWhat would you like to do?\n\n<q>uest | <s>hop | <i>nventory");
        c.setCursor(5,1);
        String choice = c.readString();
        }
}

public class ThreadTest2 extends Thread {
    Console c; 
    public void setConsole(Console con) {
        c = con;
    }
    public void run(){
        do
        {
            Money.gold = Money.gold + 1*Money.rate;
            c.setCursor(1,1);
            c.print("You currently have: " + Money.gold + " gold");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        while (true); 
    }
}
4

1 回答 1

2

听起来您需要通过控制台对象进行同步,以便一次只有一个线程可以使用它。例如你的 ThreadTest2:

public class ThreadTest2 extends Thread {
    Console c; 
    public void setConsole(Console con) {
        c = con;
    }
    public void run(){
        do
        {
            Money.gold = Money.gold + 1*Money.rate;
            synchronized(c) {
                c.setCursor(1,1);
                c.print("You currently have: " + Money.gold + " gold");
            }
            try {
                sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        while (true); 
    }
}

只要所有线程的所有控制台输出都是通过控制台对象的同一个实例,并且只要每个线程像上面的例子一样同步,它应该可以解决问题。

于 2013-06-11T18:43:21.123 回答