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