Java多线程之键盘操作练习

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

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值