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

package ccut.java.lsq;
import java.util.Date;
class ThreadTime extends Thread{
    public void run(){
        Date date=null;
        while(true){
            date=new Date();
            System.out.println(date);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class TestMain {
    public static void main(String args[]){
        ThreadTime tt =new ThreadTime();
        tt.start();
    }
}

 

运行截图:



 

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

package ccut.java.lsq;

import java.util.*;

class Numb 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;
    }
}
public class Caishu {

    public static void main(String[] args) {
        
        System.out.println("输入你猜想的数字(0~100):");
        Scanner writer = new Scanner(System.in);
        Thread num1 = new Thread();
        Thread t = new Thread(num1);
        t.start();
        
        try {
            Thread.sleep(100);
            while(true){
                int num2 = writer.nextInt();
                if(num1.getId()==num2){
                    System.out.println("猜对了!");
                    break;
                }
                else if(num1.getId()>num2){
                    System.out.println("猜小了,请重新输入");
                }
                else{
                    System.out.println("猜大了,请重新输入");
                }
            }
            
            
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

 

运行截图:

posted on 2019-12-21 14:31  螃蟹一号  阅读(158)  评论(0编辑  收藏  举报