多线程处理事务,结果统一输出

package com.temp;

import java.util.HashMap;
import java.util.Map;

/**
 * 多个线程一起运行,结果统一输出
 * */
public class MultiThreads {
	private Map<String, String> resultMap = new HashMap<String, String>();
	private int processCount = 2;

	public static void main(String[] args) {
		long begin = System.currentTimeMillis();
		MultiThreads mt = new MultiThreads();
		new TaskThread(mt).start();
		new PlanThread(mt).start();

		int count = 0;
		while (!mt.isFinished()) {
			Thread.yield();
			count++;
		}

		for (String val : mt.resultMap.values()) {
			System.out.println(val);
		}
		
		System.out.println(System.currentTimeMillis() - begin);
		
		System.out.println(count);
	}

	public int getProcessCount() {
		return processCount;
	}

	public void put(String key, String value) {
		this.resultMap.put(key, value);
		this.processCount--;
	}

	public boolean isFinished() {
		return this.processCount <= 0;
	}
}

class TaskThread extends Thread {
	private MultiThreads result;

	public TaskThread(MultiThreads result) {
		this.result = result;
	}

	@Override
	public void run() {
		try {
			sleep(1000);
			this.result.put("task", "This is a task.");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

class PlanThread extends Thread {
	private MultiThreads result;

	public PlanThread(MultiThreads result) {
		this.result = result;
	}

	@Override
	public void run() {
		try {
			sleep(1000);
			this.result.put("plan", "This is a plan.");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

 

此法适用于将一个大任务成为几个不相干的几块并行处理,提高效率。

你可能感兴趣的:(多线程,thread)