Week 16 jobs

Question 1

Topic Introduction

Write an application using Java multi-threading mechanism to achieve synchronization output time display.

Source

package com.tomotoes.sixteen;

import java.util.Date;

public class Clock {

    public static void main(String[] args) {
        new Thread(() -> Clock.tick(() -> System.out.println(new Date()))).start();
        System.out.println("正常输出。");
    }

    public static void tick(Runnable runnable) {
        while (true) {
            runnable.run();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Run shot

Question 2

Title Description

Write an application using Java multi-threading mechanism to achieve guessing game (an integer between 0 to 100 range of random numbers).

Source

package com.tomotoes.sixteen;

import java.util.Random;
import java.util.Scanner;

public class GuessNumber {
    public static void main(String[] args) {
        System.out.println("Guessing your number between 0 ~ 100");

        final int bound = 100;
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();
        final int guessNumber = new Random().nextInt(bound);

        while (number != guessNumber) {
            if (number > guessNumber) {
                System.out.println("Too greater.");
            } else {
                System.out.println("Too smaller.");
            }
            number = scanner.nextInt();
        }
        System.out.println("You guessed it.");
    }
}

Run shot

Guess you like

Origin www.cnblogs.com/jinma/p/12049163.html