题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)
代码:
package edu.ccut; import java.util.Date; public class Test_1 { public static void main(String[] args) { ClockThread clockThread = new ClockThread(); clockThread.start(); System.out.println("okk"); } } class ClockThread extends Thread { public void run() { super.run(); while (true) { System.out.println(new Date()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果:
代码:
package edu.ccut; import java.util.*; public class Test_2 { public static void main(String[] args) { Scanner input=new Scanner(System.in); Num num1=new Num(); Thread thread=new Thread(num1); thread.run(); System.out.println("请输入你猜的数字"); try { Thread.sleep(10); while(true) { Thread.sleep(10); thread.interrupt(); int num2=input.nextInt(); if(num1.getNum()==num2) { System.out.println("猜对了"); break; } else if(num2<num1.getNum()){ System.out.println("猜小了"); }else System.out.println("猜大了"); } } catch (InterruptedException e) { e.printStackTrace(); } } } class Num implements Runnable{ int num; public synchronized void run() { Random n= new Random(); num=n.nextInt(100); } public int getNum() { return num; } public void setNum(int num) { this.num=num; } }
运行结果: