前两天去面试的时候考了一题多线程的题目,后来跟朋友讨论了这道题目的多种写法,下面我把感觉性能最好的一种方法写出来,如果有好的建议,可以留言,谢谢。题目:创建多个线程来做加法运算,如线程一实现从1加到10,线程二从11加到20,一次类推,最后主线程来求多线程的和。下面这个方法主要运用了单例模式:
1、线程主体:
`public class MyThread extends Thread {
int i = 0;
Sum method;
public MyThread(int temp,Sum sumMethod){
i = temp;
method = sumMethod;
}
@Override
public void run() {
// TODO Auto-generated method stub
int beginNum = 1+ (i-1)*10;
int endNum = beginNum +9;
int sum = 0;
while(beginNum <= endNum){
sum += beginNum;
beginNum++;
}
method.addMethod(sum);
}
}
2、求和方法:
public class Sum {
private static Sum tempSum = new Sum();
static int i = 0;
int sum = 0;
private Sum() {
}
public static Sum getInstance() {
if (tempSum == null) {
tempSum = new Sum();
}
return tempSum;
}
//锁块
public void addMethod(int temp) {
synchronized (Sum.class) {
this.sum += temp;
System.out.println(this.sum);
}
}
}
注:关于锁方法还是锁块,根据业务逻辑来确定。本人认为锁块更为灵活,锁内的代码用的是同步,性能稍微慢点,如果把大量不需要同步的代码都锁住的话,会影响代码性能,我们要做到在完成需求的同时下,尽量让锁内的方法越少越好,从而提高性能
3.主函数:
public class ThreadTest {
public static void main(String[] args) {
Sum sumTemp = Sum.getInstance();
MyThread thread_one = new MyThread(1,sumTemp);
MyThread thread_two = new MyThread(2,sumTemp);
thread_one.start();
thread_two.start();
}
}
`