16次作业

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

 

package time;

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

 

package time;

import java.util.Date;

public class TimeObject implements Runnable {

    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 game;

public class test {

    public static void main(String[] args) {
        
    SynchroTest  synchro=new SynchroTest();
    synchro.guess.start();
 
    }

}
package game;
public class SynchroTest implements Runnable {
    Thread guess;
    Account account;
    SynchroTest() {
        guess = new Thread(this);
        account = new Account();
    }

    public void run() {
    if (Thread.currentThread() == guess) {
            while(true){
                System.out.println("随机数已经生成请开始游戏");
                account.withdraw();
                
            }
        }
            
    }
}
package game;

import java.util.*;

public class Account {
    Scanner sca = new Scanner(System.in);
    int a=(int) (Math.random()*100);
    int b;
     int getNum() {
         return sca.nextInt();
          }
    public synchronized void withdraw() {
        b=this.getNum();
        while (b != a) {
            if (b < a)
                System.out.println("猜小了,请重新猜");
            else
                System.out.println("猜大了,请重新猜");
             b=this.getNum();
        }
        System.out.println("恭喜猜对了");
    }
}

posted @ 2019-12-21 16:56  l刘磊  阅读(106)  评论(0编辑  收藏  举报