---
title: "一些多线程的笔记"
author: "pigfans"
date: "2012-09-05T17:43:26Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-09-05T17:43:26Z"
id: 1672178
url: "https://pigfans.iteye.com/blog/1672178"
---

1\. 保护方法原子性的同时,也要注意保护方法中使用到的变量。下面这段代码是否一定安全？

 

```
public class Counter {
		private int counter = 0;
		
		public int getCounter() {
			return counter;
		}
		
		public synchronized void add1() {
			int count = counter;
			counter = count + 1;
		}
		
		//other method
	}
```

 

不一定，如果在other method中也处理counter但是又没有保护的情况下，会出现问题，例如

 

```
public class Counter {
		private int counter = 0;
		
		public int getCounter() {
			return counter;
		}
		
		public synchronized void add1() {
			System.out.println("Enter add1");
			int count = counter;
			try {
				System.out.println("Add1 sleep");
				Thread.sleep(1000);
				System.out.println("Add1 wake up");
			} catch(Exception e) {
				e.printStackTrace();
			}
			counter = count + 1;
		}
		
		public  void add2() {
			System.out.println("Enter add2");
			int count = counter;
			counter = count + 1;
			System.out.println("Exit add2");
		}
	}
```

 

执行以下代码可以看到效果

 

```
public static void main(String[] args) throws Exception {

		final Counter c = new Counter();
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				c.add1();
			}
			
		});
		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				c.add2();
			}
			
		});
		t1.start();
		t2.start();
		Thread.sleep(2000);
		System.out.println(c.getCounter());
	}
```

 

输入结果：

Enter add1

Add1 sleep

Enter add2

Exit add2

Add1 wake up

Exit add1

1