线程同步操作共享变量时,使用synchronized可以确保共享变量的正确性,但是会降低程序的执行效率,那为什么不使用单线程执行呢?
Topic source多线程是把事情拆分下来做的。而不是一味的叠加的。如果是数组的叠加会更明显的。
public class TestAdd {
static AtomicLong atomicLong = new AtomicLong();
static long max = 10000000000L;
public static void test1() {
long start = System.currentTimeMillis();
long a = 0;
for (long i = 0;i < 10000000000L;i++){
a++;
}
long end = System.currentTimeMillis();
System.out.println(a);
System.out.println("test1 执行用时:" + (end-start));
}
public static void main(String[] args) throws InterruptedException {
TestAdd.test1();
TestAdd.test2();
}
public static void test2() throws InterruptedException {
long start = System.currentTimeMillis();
CountDownLatch countDownLatch = new CountDownLatch(10);
for (long i = 0;i < 10;i++){
Thread thread = new Thread(() -> { long z = 0; for (long j = 0;j < max/10;j++){ z++; } atomicLong.addAndGet(z); countDownLatch.countDown(); });
thread.start();
}
countDownLatch.await();
System.out.println(atomicLong.get());
long end = System.currentTimeMillis();
System.out.println("test2 执行用时:" + (end-start));
}
}
你可以试试这段代码。仅仅10个线程,叠加 10000000000 个1的时候。差别很大。
10000000000
test1 执行用时:5226
10000000000
test2 执行用时:550
多线程是工作需要。比如网页输入,一个界面需要下载图片好几秒,这个时候你不烦吗?啥也不能干如果是单线程的话。还有,订票。最后一张,究竟归谁?你这个卖票程序必须要设计成多线程的。好多咨询同时,就要开多个线程。哪个线程抢到了,就抢到了。
- 1
Top1凌度
廖老师你好!
我自己模拟了一个使用单线程和使用多线程加减100000000L次共享变量count,使用synchronized来确保多线程共享变量的值为0;
这是最后的模拟时间:
count:0 单线程执行时间:387ms
count:0 多线程执行时间:4084ms
运行多次后,执行时间以毫秒为单位,多线程执行时间,是单线程的十倍左右。
那我想问的是,既然使用多线程锁,会减低程序的性能,为什么不直接使用单线程,既可以确保值的正确性,也会比多线程运行的时间更短。那为什么不直接使用单线程来操作共享变量呢?
可能我想的不够周到,希望廖老师来解答!