第16次作业
//题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
import java.util.Date; public class Clock { public static void main(String[] args) { new Thread(new time()).start();; } public static void tick(Runnable runnable) { Date nowdata=new Date(); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(nowdata); } } }
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
public class test {
public static void main(String[] args) {
Number number = new Number();
number.beicai2.start();
number.caishu2.start();
}
class Number implements Runnable {
int beicai1,caishu1,bj;
Thread beicai2,caishu2;
boolean cai = false,sjshu = false;
public Number() {
beicai2 = new Thread(this);
caishu2 = new Thread(this);
}
public void run(){
while(true) {
panduan();
if(bj == 3){
return;
}
}
}
public synchronized void panduan(){
if(Thread.currentThread() == beicai2 && sjshu == false){
beicai1 = (int)(Math.random()*100) + 1;
System.out.println("猜数小游戏开始!" );
sjshu = true;
cai = true;
}
if(Thread.currentThread() == beicai2){
while(cai == true){
try {
wait();
} catch (InterruptedException e) {}
}
if(beicai1 > caishu1){
bj=1;
System.out.println("小了");
}else if (beicai1 < caishu1){
bj=2;
System.out.println("大了");
}else{
bj=3;
System.out.println("猜对了");
}
cai = true;
notifyAll();
}
if(Thread.currentThread() == caishu2){
while(cai == false){
try {
wait();
} catch (InterruptedException e) {}
}
Scanner reader=new Scanner(System.in);
if(bj == 1||bj==2){
caishunumber = reader.nextInt();
System.out.println("输入的数是:" + caishunumber);
}
cai = false;
}
notifyAll();
}
}

浙公网安备 33010602011771号