Java 多线程和单线程效率比较,最好是能上代码,我使用了多线程发现耗时更多,求大神解释!
代码如下:publicclassThreadBodyimplementsRunnable{publicvoidrun(){for(inti=1;i<500000000;i...
代码如下:
public class ThreadBody implements Runnable {
public void run() {
for (int i = 1; i < 500000000; i++) {
}
}
public void runSingleThread() {
for (int i = 1; i < 500000000; i++) {
}
}
}
//效率测试代码
public static void main(String[] args) {
//单线程开始
Long start1 = System.currentTimeMillis();
System.out.println("start1:"+start1);
for(int i = 0;i<20;i++)
{
ThreadBody threadBody = new ThreadBody();
threadBody.runSingleThread();
}
Long end1 = System.currentTimeMillis();
System.out.println("end1:"+end1+" 毫秒数:"+(end1-start1));//2毫秒
//单线程结束
//多线程开始
Long start2 = System.currentTimeMillis();
System.out.println("start2:"+start2);
BlockingQueue<Runnable> queue = new LinkedBlockingDeque<Runnable>();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3,6,1,TimeUnit.HOURS,queue);
ThreadBody threadBody = new ThreadBody();
for(int i = 0;i<20;i++)
{
executor.execute(threadBody);
}
Long end2 = System.currentTimeMillis();
System.out.println("end2:"+end2+" 毫秒数:"+(end2-start2));//4毫秒
//多线程结束
} 展开
public class ThreadBody implements Runnable {
public void run() {
for (int i = 1; i < 500000000; i++) {
}
}
public void runSingleThread() {
for (int i = 1; i < 500000000; i++) {
}
}
}
//效率测试代码
public static void main(String[] args) {
//单线程开始
Long start1 = System.currentTimeMillis();
System.out.println("start1:"+start1);
for(int i = 0;i<20;i++)
{
ThreadBody threadBody = new ThreadBody();
threadBody.runSingleThread();
}
Long end1 = System.currentTimeMillis();
System.out.println("end1:"+end1+" 毫秒数:"+(end1-start1));//2毫秒
//单线程结束
//多线程开始
Long start2 = System.currentTimeMillis();
System.out.println("start2:"+start2);
BlockingQueue<Runnable> queue = new LinkedBlockingDeque<Runnable>();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3,6,1,TimeUnit.HOURS,queue);
ThreadBody threadBody = new ThreadBody();
for(int i = 0;i<20;i++)
{
executor.execute(threadBody);
}
Long end2 = System.currentTimeMillis();
System.out.println("end2:"+end2+" 毫秒数:"+(end2-start2));//4毫秒
//多线程结束
} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询