一、用到的知识点:多例多线程、synchronized锁、数据共享
public class task05 {
public static void main(String[] args) {
System.out.println("请输入m到n的值,用于计算的线程数N:");
Scanner in = new Scanner(System.in);
int m = in.nextInt();
int n = in.nextInt();
int threadNumber = in.nextInt();
// 设置多线程共用存储器
NumberStore store = new NumberStore(m);
// 总共需要计算次数
int totalCalTimes = n - m;
// 平局需要计算次数
int singleCalTimes = (int) Math.floor((float) (totalCalTimes) / (float) threadNumber);
// 额外需要计算次数
int extraCalTimes = totalCalTimes % threadNumber;
System.out.println("所有线程需要执行计算次数:" + totalCalTimes + " 次");
System.out.println("执行任务的线程有:" + threadNumber + " 个");
System.out.println("每个线程需要执行基本次数:" + singleCalTimes + " 次");
System.out.println("额外需要执行的计算次数:" + extraCalTimes + " 次");
for (int i = 0; i < threadNumber; i++) {
if(extraCalTimes>0) {
new Thread(new Plusor(store, singleCalTimes+1)).start();
//对需要额外计算的平局分配
extraCalTimes--;
}else {
new Thread(new Plusor(store, singleCalTimes)).start();
}
}
in.close();
System.out.println("main Finish!");
}
}
class Plusor implements Runnable {
// 本线程的当前计算了timeCount次
private int timeCount = 0;
// 本线程最多执行的次数
private int times = 0;
// store对象
NumberStore store;
public Plusor(NumberStore store, int times) {
this.times = times;
this.store = store;
}
//线程开跑
public void run() {
System.out.println(Thread.currentThread().getName()+"start thread");
while ((this.timeCount < this.times)) {
executor();
}
System.out.println(Thread.currentThread().getName() + "——times:" + timeCount);
}
//执行计算任务
private void executor() {
NumberStore.setSumBigInteger();
this.timeCount++;
}
}
//存储与操作共享变量的存储器/操作器
class NumberStore {
//共享:累加记录总数
private static volatile BigInteger sumBigInteger = new BigInteger("0");
//共享:记录累加的索引
private static volatile int index;
//锁操作:1.总数累加 2.索引累加
public static synchronized void setSumBigInteger() {
System.out.println(Thread.currentThread().getName()+"——index:"+index);
index++;
sumBigInteger = sumBigInteger.add(BigInteger.valueOf(index));
System.out.println(Thread.currentThread().getName()+"——total:"+sumBigInteger);
}
public NumberStore(int m) {
NumberStore.index=m;
sumBigInteger = sumBigInteger.add(BigInteger.valueOf(m));
}
}
二、个人做题总结
关于解题的要点:
多线程共享变量有两个:总数、累加的索引 多线程需要加锁的操作:总数的计算、索引的累加
关于实践的总结:
(一)如何在启动线程前设定一个全局共享变量(而不是在线程中设定一个常量)?
方案:创建一个存储器(对象),所有的线程从该存储器读取数据。同时对该存储器的数据加volatile同步工作缓冲区,修改操作的方法加锁synchronized。
应用场景
需要volatile的变量 需要synchronized的方法
缘由/原理:
由于多线程启动顺序不同,导致最先开启的线程在开始运算赋值后的共享变量,会被后开启的线程赋值所覆盖 使用存储器可以模块化操作,将共享变量和加锁的方法与线程隔离开,保证不被相互影响。 在开启线程前就将变量和方法进行初始化,后续的线程操作都将实时的操作这个存储器。
(二)synchronized应该放在哪一层?
synchronized应该放在最内层可以避免加锁与调用之间存在空白,导致加锁不严谨,数据混乱。
放在最外层:混乱
放在最里层:正常
(三)普通开发与多线程开发区别?
理解:正常的开发其实就是单线程(main)开发,所以Thread的方法可以在main直接使用,只不过单线程中没啥用(说明Thead的方法可以递归到最底层使用):
主动:
线程睡眠等待 Thread.sleep(1000);
代码块/函数加锁 synchronized字段
工作区缓存同步 volatile字段
中断线程 实例.interrupt()
被动:
等待notify唤醒 wait()
唤醒线程 notify()
唤醒所有线程 notifyAll()
...
(四)在线程执行基本任务的时候,如何随机让某些线程执行附加的任务?
在main主线程分配任务的时候就计算分配好。不要在线程内进行判断再分配,因为这样可能会干扰的线程的基本任务。
(五)对于线程要执行多少任务,要在main函数中就分配好,而不是在线程中进行判断
有错误欢迎指正哈!