题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
代码:
Time类实现Runnable接口
package cn.hou;
import java.util.Date;
/**
* 导入包
* @author ASUS
*
*/
public class Time implements Runnable {//实现Runnable接口
public void run() {
Date date=null; //对象置为null
while(true){
date=new Date();
System.out.println(date);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Test类
package cn.hou;
import java.util.*;
import java.text.*;
/**
*
* @author ASUS
*
*/
public class Test {
public static void main(String[] args) {
System.out.println("时间的同步输出显示如下:");
Thread thread=new Thread(new Time() );
thread.start(); //进入等待序列
}
}
截图
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)
代码:
Ran类
package cn.houhou;
import java.util.Random;
/**
* 随机数范围0~100之间的整数
* @author ASUS
*
*/
public class Ran 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;
}
}
Main类
package cn.houhou;
/**
* 猜数字
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Ran randNum = new Ran();
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();
}
}
}
截图