29
2020
02

多线程 处理数据 Thread demo

多线程demo  处理多片数据范围 示例:

ThreadDemo:

一,继承 Thread的用法

public class ThreadDemo extends Thread {

	private int startIndex;
	private int size;

	public ThreadDemo(int startIndex, int size) {
		this.startIndex = startIndex;
		this.size = size;
	}

	@Override
	public void run() {
		// 处理逻辑......
		this.synPorduct();
	}

	public void synPorduct() {
		// 处理逻辑......
		System.out.println("开始本次任务范围:" + this.startIndex + "~" + this.size);
		// 批量获取 数据
		// List list = dao.selectInfo(this.startIndex,this.startIndex);
		//System.out.println("本次处理数据"+list.size()+"条");
		System.out.println("本次全部结束!!!");
	}
}

调用示例:


public class StartThreadDemo {

	public static void main(String[] args) {
		try {
			new ThreadDemo(0, 100).start();
			new ThreadDemo(101, 100).start();
			new ThreadDemo(201, 100).start();
			new ThreadDemo(301, 100).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}

运行结果示例:


image.png


二,继承 Runnable 的用法

public class ThreadDemo {

	public static void main(String[] args) {
		Thread sub = new Thread(new LimitSub(0, 100));
		sub.start();
		new Thread(new LimitSub(101, 100)).start();
		new Thread(new LimitSub(201, 100)).start();
		new Thread(new LimitSub(301, 100)).start();
	}

}

class LimitSub extends Limit implements Runnable {

	private int startIndex;
	private int size;

	public LimitSub(int startIndex, int size) {
		super(startIndex, size);
		this.startIndex = startIndex;
		this.size = size;
	}

	@Override
	public void run() {
		Thread.currentThread().setName("本次范围起始:" + this.startIndex);
		System.out.println(Thread.currentThread().getName());
		this.synPorduct();
	}

	public void synPorduct() {
		// 处理逻辑......
		System.out.println("开始本次任务范围:" + this.startIndex + "~" + this.size);
		// 批量获取 数据
		// List list = dao.selectInfo(this.startIndex,this.startIndex);
		// System.out.println("本次处理数据"+list.size()+"条");
		System.out.println("本次全部结束!!!");
	}
}

class Limit {
	private int startIndex;
	private int size;

	public Limit(int startIndex, int size) {
		this.startIndex = startIndex;
		this.size = size;
	}

}


运行结果示例:


image.png

仅供参考!!!

« 上一篇 下一篇 »