题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
代码:
package chuanchuan; public class Test { public static void main(String[] args) { TreadTime tt=new TreadTime(); //Thread th=new Thread(Object); tt.start(); } }
package chuanchuan; import java.util.Date; public class TreadTime extends Thread { public void run(){ Date date; while (true){ date=new Date(); System.out.println(date); try { this.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果:
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
代码:
package chuanchuan; import java.util.*; class Threadnum extends Thread{ Thread output; int num1,num2; Threadnum(){ output = new Thread(this); } public void run() { Random n = new Random(); num1 = n.nextInt(100); try { output.sleep(4000); Judge(); } catch (InterruptedException e) { e.printStackTrace(); } } public void Judge() { while(true){ Scanner reader = new Scanner(System.in); num2 = reader.nextInt(); if(num1==num2) { System.out.println("猜对了正确数字为:"+num1); break; }else if(num1>num2) { System.out.println("猜小了"); }else { System.out.println("猜大了"); } } } } public class Test12_19_2 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入猜测的数字"); Threadnum num = new Threadnum(); num.output.start(); } }
运行截图: