java-第十六周作业

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

代码:

主类:

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        threadc t = new threadc();
        t.start();
        

    }

}

threadc类

import java.util.Date;

public class threadc extends Thread{
    Date date = null;

    public void run() {
        
        while(true){

            //Date date = new Date(10);
            System.out.println(new Date());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }

}

 

截图:

java-第十六周作业_第1张图片

 

 

 

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

代码:

Test主类:

package ccut.cn.com;
import java.util.*;
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("请猜想一个数字,范围在0-100中:");
        Scanner reader = new Scanner(System.in);
        threaddemo num1 = new threaddemo();
        Thread t = new Thread(num1);
        t.start();
        
        try {
            Thread.sleep(100);
            while(true){
                int num2 = reader.nextInt();
                if(num1.getNum()==num2){
                    System.out.println("恭喜你,答对了!");
                    break;
                }
                else if(num1.getNum()>num2){
                    System.out.println("太小了");
                }
                else{
                    System.out.println("太大了");
                }
            }
            
            
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

threaddemo类:

package ccut.cn.com;

import java.util.Random;

public class threaddemo extends Thread{
    int num;
    public int getNum(){
        return num;
    }
    public void setNum(int num){
        this.num = num;
    
    }
    public void run(){
        Random b = new Random();
        num = b.nextInt(100);
    }
    

}

 

 

 

截图:

java-第十六周作业_第2张图片

你可能感兴趣的:(java-第十六周作业)