多线程实现输出当前时间,和猜数字游戏
题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
题目1:
package Test; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class PrintCurrentTIme { public static void main(String[] args) { // TODO Auto-generated method stub Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(date); System.out.println(time); } },0, 1000); } }
运行结果:
题目2:
package Test; import java.util.Random; import java.util.Scanner; public class GuessNumber { public static void main(String[] args) { // TODO Auto-generated method stub NumberTest number = new NumberTest(); RandomNumberRun ran = new RandomNumberRun(number); GiveNumberRun give = new GiveNumberRun(number); ran.start(); give.start(); } } class RandomNumberRun extends Thread { NumberTest number1; RandomNumberRun(NumberTest number1) { this.number1 = number1; } @Override public void run() { // TODO Auto-generated method stub Random ran = new Random(); while (true) { synchronized (number1) { while (number1.flag) { try { number1.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } int num = ran.nextInt(101); number1.setNum1(num); number1.notifyAll(); number1.flag = true; } } } } class GiveNumberRun extends Thread { NumberTest number2; GiveNumberRun(NumberTest number2) { this.number2 = number2; } @Override public void run() { // TODO Auto-generated method stub Scanner read = new Scanner(System.in); while (true) { System.out.println("请输入0~100的数字!!!"); synchronized (number2) { while (!number2.flag) { try { number2.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } number2.setNum2(read.nextInt()); number2.flag = false; number2.PrintRes(); number2.notifyAll(); } } } } class NumberTest { public boolean flag = false; private int num1; private int num2; public int getNum1() { return num1; } public void setNum1(int num1) { this.num1 = num1; } public int getNum2() { return num2; } public void setNum2(int num2) { this.num2 = num2; } public void PrintRes() { if (num1 > num2) { System.out.println("小了"); } else if (num1 < num2) { System.out.println("大了"); } else { System.out.println("猜对了!!!"); } } }
运行结果: