第16周作业

题目1:

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

代码:

package bean;

import java.util.Date;

public class TimeObject implements Runnable{

	@Override
	public void run(){
		Date date =null;
		while(true){
			date=new Date();
			System.out.println(date);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

}

  

package demo;

import bean.TimeObject;

public class test {
	public static void main(String[] args) {
		Thread t=new Thread(new TimeObject());
		t.start();
		

	}

}

  

运行结果

题目2:

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

代码:

package demo;

import java.util.Scanner;

class Threadmethod implements Runnable{
    Thread Guess,SetNum;  
    int num,RandomNum,flag;
    boolean a=false,b=false;
    public Threadmethod(){
    	Guess=new Thread(this);
    	SetNum=new Thread(this);
    }
    
    public void run(){
        while(true){
            compare();  
            if(flag==3)
                return;
        }
    }
    
    public synchronized void compare(){
        if(Thread.currentThread()==Guess&&b==false){
        	RandomNum=(int)(Math.random()*100)+1;  
            System.out.println("随机数生成,游戏开始");
            a=true;
            b=true;    
        }
        if(Thread.currentThread()==Guess){
            if(a==true){
                try {
                    wait(); 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(num<RandomNum){   
                System.out.println("抱歉,您猜小了!");
                flag=1;
            }
            else if(num>RandomNum){
                System.out.println("抱歉,您猜大了!");
                flag=2;
            }
            else if(num==RandomNum){
                System.out.println("恭喜,您猜对了!");
                flag=3;
            }
            a=true;
            notifyAll();  
        }
        if(Thread.currentThread()==SetNum){
              while(a==false){
            	  try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
              }  
              if(flag<3){
                  System.out.println("请输入您猜测的数");
                  Scanner reader=new Scanner(System.in);
                  num=reader.nextInt();   
              }
              a=false;
        }
        notifyAll();  
    }
}


public class ts {

	public static void main(String[] args) {
		 Threadmethod tm=new Threadmethod();  
		 tm.Guess.start();  
		 tm.SetNum.start();  
	}

}

运行结果

posted @ 2019-12-21 21:06  胡烙懿  阅读(208)  评论(0编辑  收藏  举报