gpt4 book ai didi

java - 为什么客户端线程只执行一次就销毁了? Java TCP 套接字

转载 作者:行者123 更新时间:2023-11-29 08:18:52 25 4
gpt4 key购买 nike

我希望我的客户端类运行一个线程,该线程每 5 秒连续向服务器发送字符串信息(顺序)。但是线程在发送第一个订单后被销毁。我不知道为什么以及如何阻止它,有人可以帮助我吗?

下面的代码;

public class Cashier implements Runnable
{
private static final int MAX_DELAY = 5000;
static OrderList orderList;
static Socket socket;
static PrintWriter out = null;
static BufferedReader in = null;

int orderNumber = 0;
public String order, strorderNumber;

public static void main(String[] args){


Cashier newCashier = new Cashier();
Thread cashierThread = new Thread(newCashier);
cashierThread.setName("Olaf");
cashierThread.setDaemon(false);
cashierThread.start();

try {
socket = new Socket("127.0.0.1", 4444);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void run()
{
try{
Date now = new Date();
Format fTime = new SimpleDateFormat("hh:mm:ss a");
order = ("Order made by " + Thread.currentThread().getName()+ " at " + fTime.format(now)+ "\n");

out.print(order);

Random randomNumber = new Random();
Thread.sleep(randomNumber.nextInt(MAX_DELAY));
} catch (InterruptedException exception){
System.out.println("Olafs interrupted exception");
}

}
}

最佳答案

您的类的 run 方法不包含循环,因此它将执行它必须执行的操作一次,然后跳出底部,有效地终止线程。

如果你想让它连续运行,你需要这样的东西:

public void run() {
boolean keepGoing = true;
while (keepGoing) {
try {
Date now = new Date();
Format fTime = new SimpleDateFormat("hh:mm:ss a");
order = "Order made by " + Thread.currentThread().getName()
+ " at " + fTime.format(now)+ "\n";

out.print(order);

Random randomNumber = new Random();
Thread.sleep(randomNumber.nextInt(MAX_DELAY));
} catch (InterruptedException exception){
System.out.println("Olafs interrupted exception");
keepGoing = false;
}
}
}

关于java - 为什么客户端线程只执行一次就销毁了? Java TCP 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1978451/

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