Java多线程之键盘操作练习

Java多线程之键盘操作练习Java 多线程之键盘操作练习 GiveLetterTh javapackageg thread1 publicclassG Letterletter charcStart a cEnd z intsleepLeng 5000 publicvoidse 键盘输入练习线程 a 每次在控制台给出 a z 任意字符 然后在控制台输入对应的字符 b 线

Java多线程之键盘操作练习

GiveLetterThread.java

package gxy.thread1;

public class GiveLetterThread extends Thread {
   

    Letter letter;
    char cStart='a',cEnd='z';
    int sleepLength=5000;


    public void setLetter(Letter letter) {
        this.letter = letter;
    }


    public void setSleepLength(int sleepLength) {
        this.sleepLength = sleepLength;
    }


    @Override
    public void run() {
        char c = cStart;
        while(true){
            letter.setC(c);
            System.out.printf("显示的字符:%c\n",letter.getC());
            try {
                sleep(sleepLength);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            c = (char)(c+1);
            if(c>cEnd){
                c= cStart;
            }
        }
    }
}

InputLetterThread.java

package gxy.thread1;

import java.util.Scanner;

public class InputLetterThread extends Thread {
   

    Scanner reader;
    Letter letter;
    int score = 0;

    public InputLetterThread() {
        reader = new Scanner(System.in);
    }

    public void setLetter(Letter letter) {
        this.letter = letter;
    }

    @Override
    public void run() {
        while (true) {
            String line = reader.nextLine();
            char c = line.charAt(0);
            if(c==letter.getC()){
                score++;
                System.out.printf("\t\t输入对了,目前分数%d\n",score);

            }else{
                System.out.printf("\t\t输入错了,目前分数%d\n",score);
            }
            if(c=='#'){
                System.exit(0);
            }

        }
    }
}

Letter.java

package gxy.thread1;

public class Letter {

    char c = '\0';

    public char getC() {
        return c;
    }

    public void setC(char c) {
        this.c = c;
    }


}

TypeKey.java

package gxy.thread1;

public class TypeKey {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.err.println("键盘练习,输入#结束程序");
        System.out.printf("输入显示的字母,回车\n");
        Letter letter = new Letter();
        GiveLetterThread giveLetterThread;
        InputLetterThread inputLetterThread;

        giveLetterThread = new GiveLetterThread();
        giveLetterThread.setLetter(letter);
        giveLetterThread.setSleepLength(3200);

        inputLetterThread = new InputLetterThread();
        inputLetterThread.setLetter(letter);;

        giveLetterThread.start();

        inputLetterThread.start();

    }

}
编程小号
上一篇 2025-01-09 19:21
下一篇 2025-01-09 19:11

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/106235.html