一个坏掉的番茄
Published on 2017-09-02 11:31 in 暂未分类 with Simon Ma

第16周作业

题目1

题目简介

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

源代码

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();
			}
		}
	}
}

运行截图

题目2

题目描述

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

Util 类

package com.tomotoes.probleam.sixteen;

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

public class Util {
	public static Random random = new Random();
	public static Scanner scanner = new Scanner(System.in);
	public static int bound;

	public static void setRandomBound(int bound) {
		Util.bound = bound;
	}

	public static int getRandomNumber() {
		return random.nextInt(bound);
	}

	public static int getInputNumber() {
		return scanner.nextInt();
	}

	public static void log(Object o) {
		System.out.println(o.toString());
	}
}

TaskPool 类

package com.tomotoes.probleam.sixteen;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import java.util.stream.IntStream;

public class TaskPool<T> {
	public int count;
	public ExecutorService pool;
	public ArrayList<Future<T>> results;
	public Callable<T> task;
	public Predicate<Future<T>> finished;

	public TaskPool(int count, Callable<T> task, Predicate<Future<T>> finished) {
		this.count = count;
		this.pool = Executors.newFixedThreadPool(count);
		this.results = new ArrayList<>(count);
		this.task = task;
		this.finished = finished;
		this.run();
	}

	public void run() {
		results.clear();
		IntStream.range(0, count).forEach(i -> {
			results.add(pool.submit(task));
		});
	}

	public boolean finished() {
		return results.stream().anyMatch(finished);
	}

	public void end() {
		pool.shutdown();
	}
}

主类

package com.tomotoes.probleam.sixteen;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.function.Predicate;

public class Main {

	public static void main(String[] args) {
		Util.log("Guessing random number between 0 ~ 100.");
		Util.setRandomBound(100);
		final int GOAL = Util.getRandomNumber();

		Util.log("Please input the count of robots that compete with you:");
		final int countOfThreads = Util.getInputNumber();
		if (countOfThreads < 1) {
			throw new Error("The count of robots must be greater than one.");
		}

		List<Integer> hadFailedList = Collections.synchronizedList(new ArrayList<>());
		Callable<Boolean> guess = () -> {
			int number = Util.getRandomNumber();
			while (hadFailedList.contains(number)) {
				number = Util.getRandomNumber();
			}
			hadFailedList.add(number);
			return number == GOAL;
		};
		Predicate<Future<Boolean>> guessed = f -> {
			try {
				return f.get();
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
			return false;
		};
		TaskPool<Boolean> tasks = new TaskPool<>(countOfThreads, guess, guessed);

		Util.log("Please input your number:");
		int yourNumber = Util.getInputNumber();

		while (yourNumber != GOAL && !tasks.finished()) {
			Util.log("Too " + (yourNumber > GOAL ? "greater." : "smaller."));
			yourNumber = Util.getInputNumber();
			tasks.run();
		}
		Util.log((yourNumber == GOAL ? "You" : "Thread") + " guessd it.");
		Util.log("Random number is " + GOAL + ".");
		tasks.end();
	}
}

运行截图


posted @ 2019-12-16 15:02  SimonMa  阅读(235)  评论(0编辑  收藏  举报