在Java如何保證方法是線程安全的
廢話開篇
都說Java程序好些,但是我覺得Java編程這東西,沒個十年八年的真不敢說自己精通Java編程,由於工作原因,開始轉戰Java多線程,以前沒怎麼接觸過,所以想留點腳印在這兩條路上。
切入正題
開門見山,今天看到別人寫的一段關於方法是否線程安全的文章,比較簡單,但是由於自己也是剛開始入門,所以就邁下了第一步。由於註釋還算比較詳細,所以就不廢話了,直接上code.
此方法不是線程安全的
1 /**
2 * @Title: NotThreadSafeCounter.java
3 * @Package never.uncategory
4 * @Description: * The method is not thread-safe, because the
5 * counter++ operation is not atomic, which means it consists
6 * more than one atomic operations. In this case, one is
7 * accessing value and the other is increasing the value by one.
8 * @author "Never" xzllc2010#gmail.com
9 * @date Mar 14, 2014 7:44:24 PM
10 */
11 /*
12
13 */
14 package never.uncategory;
15
16 public class NotThreadSafeCounter extends Thread {
17
18 private static int counter = 0;
19
20 public void run() {
21 System.out.println("counter:" + getCount());
22 }
23
24 public static int getCount() {
25
26 try {
27 Thread.sleep(1500);
28 } catch (Exception e) {
29 e.printStackTrace();
30 }
31 return counter++;
32
33 }
34
35 public static void main(String[] args) {
36
37 for (int i = 0; i < 5; i++) {
38 new NotThreadSafeCounter()。start();
39 }
40 }
41
42 }
View Code
此方法是線程安全的(synchronized)
1 /**
2 * @Title: ThreadSafeCounter.java
3 * @Package never.uncategory
4 * @Description: Adding synchronized to this method will makes
5 * it thread-safe,When synchronized is added to a static method,
6 * the Class object is the object which is locked.If the method
7 * is not static, then adding synchronized keyword willsynchronize
8 * the instance of the class, not the Class object.
9 * @author "Never" xzllc2010#gmail.com
10 * @date Mar 14, 2014 8:09:45 PM
11 */
12 package never.uncategory;
13
14 public class ThreadSafeCounter {
15
16 private static int counter = 0;
17
18 public void run() {