第16周作业
题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
主代码:
package org.ccut.pack18;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 系统时间同步
*/
public class TimeSync implements Runnable {
@Override
public void run() {
Date date = null;
while (true) {
date = new Date();
// 时间格式化对象
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EE");
System.out.println(dateFormat.format(date));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试代码:
package org.ccut.pack18;
public class TestTimeSync {
public static void main(String[] args) {
System.out.println("当前时间:");
Thread t = new Thread(new TimeSync());
t.start();
}
}
运行结果:
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
主代码:
package org.ccut.pack19;
import java.util.Random;
public class PickNumberGame 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;
}
}
测试代码:
package org.ccut.pack19;
import java.util.Scanner;
public class MainTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PickNumberGame randNum = new PickNumberGame();
// 创建线程对象
Thread t = new Thread(randNum);
t.start();
System.out.println("猜数字游戏开始!输入一个数字:");
try {
Thread.sleep(1000);
while (true) {
t.interrupt();
int num = scanner.nextInt();
if (randNum.getNum() == num) {
System.out.println("猜对了");
break;
} else if (num < randNum.getNum()) {
System.out.println("猜小了");
} else if (num > randNum.getNum()) {
System.out.println("猜大了");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果: