在了解线程和更改多个线程中的变量时遇到问题

时间:2019-05-27 07:01:31

标签: java multithreading atomic

我正在尝试限制服务器上的客户端数量,所以我只是在服务器满时从服务器发送消息,并通过为他结束进程在客户端中打印它。但是由于我使用多个线程,所以无法停止writeMessage线程

尝试过AtomicBoolean,但我没有工作

public class Client {

    private static final Logger LOGGER = LogManager.getLogger();
    private BufferedReader consoleReader;
    private String name;
    private String address;
    private int port;
    private Thread writeMessage, readMessage;
    private ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
    private LocalTime dTime = zonedDateTime.toLocalTime();
    private Net net;
    private AtomicBoolean running = new AtomicBoolean(true);

    public Client(String address, int port) {
        this.address = address;
        this.port = port;
        net = new Net(address, port);
        consoleReader = new BufferedReader(new InputStreamReader(System.in));
        printName();
        readMessage();
        writeMessage();
    }

    private void printName() {
        System.out.println("Print your name:");
        try {
            name = consoleReader.readLine();
            while (NameValidator.nameIsValid(name)) {
                System.out.println("Name should contain more than 1 letter");
                name = consoleReader.readLine();
            }
            net.send(name + "\n");
        } catch (IOException e) {
            LOGGER.error(e);
        }
    }

    private void readMessage() {
        readMessage = new Thread(() -> {
            String str = net.receive();
            while (net.isConnected()) {
                if ("full".equals(str)) {
                    System.out.println("server is full");
                    running.set(false);
                    break;
                } else {
                    System.out.println(str);
                    str = net.receive();
                }
            }
            net.offService();
        }, "readMessage");
        readMessage.start();
    }

    private void writeMessage() {
        writeMessage = new Thread(() -> {
            while (running.get()) {
                String userWord;
                try {
                    String time = dTime.getHour() + ":" + dTime.getMinute() + ":" + dTime.getSecond();
                    userWord = consoleReader.readLine();
                    if (userWord.equals("quit")) {
                        net.send(userWord + "\n");
                        ClientAmountGenerator.decrement();
                        running.set(false);
                    } else {
                        net.send("(" + time + ") " + name + " says : " + userWord + "\n");
                    }
                } catch (IOException e) {
                    LOGGER.error(e);
                }
            }
            net.offService();
        }, "writeMessage");
        writeMessage.start();
    }
}

我想将运行更改为“ false”,因此,如果writeMessage线程从服务器获取消息“ full”,则将无法工作

0 个答案:

没有答案