在这篇文章里,我们首先阐述什么是同步,不同步有什么问题,然后讨论可以采取哪些措施控制同步,接下来我们会仿照回顾网络通信时那样,构建一个服务器端的“线程池”,JDK为我们提供了一个很大的concurrent工具包,最后我们会对里面的内容进行探索。
为什么要线程同步?
说到线程同步,大部分情况下, 我们是在针对“单对象多线程”的情况进行讨论,一般会将其分成两部分,一部分是关于“共享变量”,一部分关于“执行步骤”。
共享变量
当我们在线程对象(Runnable)中定义了全局变量,run方法会修改该变量时,如果有多个线程同时使用该线程对象,那么就会造成全局变量的值被同时修改,造成错误。我们来看下面的代码:
1 class MyRunner implements Runnable 2 { 3 public int sum = 0; 4 5 public void run() 6 { 7 System.out.println(Thread.currentThread().getName() + " Start."); 8 for (int i = 1; i <= 100; i++) 9 { 10 sum += i; 11 } 12 try { 13 Thread.sleep(500); 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 System.out.println(Thread.currentThread().getName() + " --- The value of sum is " + sum); 18 System.out.println(Thread.currentThread().getName() + " End."); 19 } 20 } 21 22 23 private static void sharedVaribleTest() throws InterruptedException 24 { 25 MyRunner runner = new MyRunner(); 26 Thread thread1 = new Thread(runner); 27 Thread thread2 = new Thread(runner); 28 thread1.setDaemon(true); 29 thread2.setDaemon(true); 30 thread1.start(); 31 thread2.start(); 32 thread1.join(); 33 thread2.join(); 34 }