第16周作业


题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。

题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。

1、

 

package ccut.edu.cn;
/**
 * 实现时间的同步输出显示
 */
import java.text.SimpleDateFormat;
import java.util.Date;
public class Time implements Runnable{
    Date date;
    public void run() {
        while(true){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
            String time = sdf.format(date);
            System.out.println(time);
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                System.out.println(e);
            }
        }        
    }
}

 

 

 

import java.util.Scanner;
public class CurrentTime {
    public static void main(String[] args) {
        Thread t=new Thread(new Time() );
        t.start();
    }
}

运行截图

 

2、

 

package ccut.edu.cn;
/**
 * 实现猜数字游戏
 */
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Thread implements Runnable{//实现线程接口
    Scanner s=new Scanner(System.in);
    int flag;//中间判断变量
    public void run() {
        while(true){
            System.out.println("输入数字");
            int c=s.nextInt();
            int a=(int)(Math.random()*100);//生成随机数
            if(c>=a){
                System.out.println("猜大了");
            }else if(c<a)
                System.out.println("猜小了");
            else System.out.println("猜对了");
         //   System.out.println(a);
            try{
                Thread.sleep(1000);    //暂停            
            }catch(InterruptedException e){
                System.out.println(e);
            }      
        } 
    }
}

 

 

 

package ccut.edu.cn;
import java.util.Scanner;
public class CurrentTime0 {
    public static void main(String[] args) {
        Thread t=new Thread(new thread() );
        t.start();
    }
}

运行截图

posted @ 2019-12-22 22:29  黄晓天20194672  阅读(172)  评论(0编辑  收藏  举报