CPU给每个线程分配CPU时间片。 上下文切换并发执行并不一定比串行快?这是因为线程有创建和上下文切换的开销。 /** * 不同的累加操作下,现成并发执行与串行的性能差异测试 * Created by niuya on 2018/6/14. */ public class ConcurrencyTest { private static final long count = 1000000000l; public static void main(String[] args) throws InterruptedException { concurrency(); serial(); } private static void concurrency() throws InterruptedException { long start = System.currentTimeMillis(); Thread thread = new Thread(new Runnable() { @Override public void run() { int a = 0; for (long i = 0; i < count; i++) { a += 5; } System.out.println("concurrency :" + " a="+a); } }); thread.start(); int b = 0; for (long i = 0; i < count; i++) { b--; } long time = System.currentTimeMillis() - start; thread.join(); System.out.println("concurrency :" + time+"ms,b="+b); } private static void serial() { long start = System.currentTimeMillis(); int a = 0; for (long i = 0; i < count; i++) { a += 5; } int b = 0; for (long i = 0; i < count; i++) { b--; } long time = System.currentTimeMillis() - start; System.out.println("serial:" + time+"ms,b="+b+",a="+a); } } 这里,使用vmstat测量上下文切换的次数。 如何减少上下文切换? 死锁/** * 死锁示例 * Created by niuya on 2018/6/14. */ public class DeadLockDemo { private static String A = "A"; private static String B = "B"; public static void main(String[] args) { new DeadLockDemo().deadLock(); } private void deadLock(){ Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized (A) { try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (B) { System.out.println("1"); } } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { synchronized (B) { synchronized (A) { System.out.println("2"); } } } }); t1.start(); t2.start(); } } 避免死锁的几个常见方法: 资源限制 资源限制是指在进行并发编程时,程序的执行速度受限于计算机硬件资源或软件资源 |
|
来自: liang1234_ > 《java多线程》