gpt4 book ai didi

Java线程并发

转载 作者:行者123 更新时间:2023-11-30 09:21:20 25 4
gpt4 key购买 nike

所以我希望一个线程不断更新你有多少“金币”,而另一个线程运行游戏。

问题是每个光标都在改变,我首先通过让它们不同步, sleep 来修复它,但是当我想让用户输入文本时,它会转到第一行。有人知道如何解决这个问题吗?

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);
}
}

最佳答案

听起来您需要通过控制台对象进行同步,这样一次只有一个线程可以使用它。例如,您的 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);
}
}

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

关于Java线程并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com