第16周作业
题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
代码:
object类:
package jhy; import java.util.Date; public class object implements Runnable { public void run() { Date date=null; while(true) { date=new Date(); System.out.println(date); try{ Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } } } }
Test类:
package jhy; import jhy.object; public class Test { public static void main(String[] arge) { Thread t=new Thread(new object()); t.start(); } }
运行截图:
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)
代码:
package jhy; import java.util.*; public class Threadshu extends Thread { Thread output; int num1,num2; Threadshu(){ output = new Thread(this); } public void panduan() { 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 void run() {
Random n = new Random();
num1 = n.nextInt(100);
try {
output.sleep(4000);
panduan();
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package jhy; import java.util.*; public class Test121 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入猜测的数字"); Threadshu num = new Threadshu(); num.output.start(); } }
运行截图: