线程安全问题的现象
首先让我们考虑一个问题:
class Demo implements Runnable{
private int num = 100;
//实现Runnable接口,覆盖run方法
public void run(){
show();
}
public void show(){
while (true){
if (num>0){
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Demo d = new Demo();
Thread t1 = new Thread(d);
Thread t2 = new Thread(d);
Thread t3 = new Thread(d);
Thread t4 = new Thread(d);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
我们假设这样一种情况,当num=1时,执行Thread-0的时候,恰巧执行完if(num>0)的判断语句后切换到了1并且执行完System语句又回到Thread-0,那么将会出现问题,Thread-0线程将会输出-1.(由于线程切换是随机的而导致的错误),注意由于类是覆盖Runnable接口的run方法,接口没有声明过异常,因此不能在run方法后通过throws抛出异常,而只能使用try{}catch{}块。
线程安全问题的原因
原因:
1、多个线程在操作共享的数据。
2、操作共享数据的线程代码有多条,一个线程正在进行,还没有结束的时候其他线程进行了一些操作。
同步代码块synchronized
解决思路:就是将多条操作共享数据的线程代码封装起来,当有线程在执行这些代码的时候,其他线程不可以参与运算,必须要把当前线程都执行完毕后,其他线程才可以参与运算。
class Demo implements Runnable{
private int num = 100;
private Object lock = new Object();
//实现Runnable接口,覆盖run方法
public void run(){
while (true){
synchronized (lock){
if (num>0){
try{
Thread.sleep(10);
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
}
}
在Java中使用同步代码块就可以解决这个问题,同步代码块的格式:
synchronize(对象){
需要被同步的代码块;
}
其中的“对象”相当于一个锁,只有执行完该代码块才能释放该对象锁,下一个线程才能执行并锁定该对象。
给指定对象加锁
/**
* 银行账户类
*/
class Account {
String name;
float amount;
public Account(String name, float amount) {
this.name = name;
this.amount = amount;
}
//存钱
public void deposit(float amt) {
amount += amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//取钱
public void withdraw(float amt) {
amount -= amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public float getBalance() {
return amount;
}
}
/**
* 账户操作类
*/
class AccountOperator implements Runnable{
private Account account;
public AccountOperator(Account account) {
this.account = account;
}
public void run() {
synchronized (account) {
account.deposit(500);
account.withdraw(500);
System.out.println(Thread.currentThread().getName() + ":" + account.getBalance());
}
}
}
调用代码:
Account account = new Account("zhang san", 10000.0f);
AccountOperator accountOperator = new AccountOperator(account);
final int THREAD_NUM = 5;
Thread threads[] = new Thread[THREAD_NUM];
for (int i = 0; i < THREAD_NUM; i ++) {
threads[i] = new Thread(accountOperator, "Thread" + i);
threads[i].start();
}
结果:
Thread3:10000.0
Thread2:10000.0
Thread1:10000.0
Thread4:10000.0
Thread0:10000.0
在AccountOperator 类中的run方法里,我们用synchronized 给account对象加了锁。这时,当一个线程访问account对象时,其他试图访问account对象的线程将会阻塞,直到该线程访问account对象结束。也就是说谁拿到那个锁谁就可以运行它所控制的那段代码。
当有一个明确的对象作为锁时,就可以用类似下面这样的方式写程序。
public void method3(SomeObject obj)
{
//obj 锁定的对象
synchronized(obj)
{
// todo
}
}
当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的对象来充当锁:
class Test implements Runnable
{
private byte[] lock = new byte[0];
//private Object lock = new Object(); // 特殊的instance变量
public void method()
{
synchronized(lock) {
// todo 同步代码块
}
}
public void run() {
method();
}
}
说明:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码。
synchronized总结
A. 无论synchronized关键字加在方法上还是对象上,如果它作用的对象是非静态的,则它取得的锁是对象;如果synchronized作用的对象是一个静态方法或一个类,则它取得的锁是对类,该类所有的对象同一把锁。
B. 每个对象只有一个锁(lock)与之相关联,谁拿到这个锁谁就可以运行它所控制的那段代码。
C. 实现同步是要很大的系统开销作为代价的,因为同步外的线程都会判断同步锁,甚至可能造成死锁,所以尽量避免无谓的同步控制。
同步的好处:解决了线程的安全问题
同步的弊端:相对降低了效率,因为同步外的线程都会判断同步锁
同步的前提:同步中必须有多个线程,并使用同一个锁
class Test implements Runnable
{
public void method()
{
synchronized(lock) {
// todo 同步代码块
}
}
public void run() {
private byte[] lock = new byte[0];
//private Object lock = new Object(); // 特殊的instance变量
method();
}
}
如上所示的修改导致每个线程开启运行自己的run方法时,每个run方法都有自己的局部变量lock,因此不是同一个锁。而像正确的方式时,栈中保存的多个引用都指向同一个锁(原理类似于深复制,浅复制),因此可以保证安全。
同步函数
先来看一个例子:
class Bank{
private int sum;
public void add(int num){
sum+=num;
System.out.println("sum="+sum);
}
}
class Cus implements Runnable{
Bank b = new Bank();//对象b是多个线程的共享数据
public void run(){
for (int x=0;x<3;x++){
b.add(100);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
当一个线程执行sum+=num;之后,还没有执行System语句cpu变切换到其他线程就造成如上现象。
修改(加上同步块):
class Bank{
private int sum;
private Object lock = new Object();
public void add(int num){
synchronized (lock){
sum+=num;
System.out.println("name="+Thread.currentThread().getName()+"sum="+sum);
}
}
}
仔细观察上述代码,同步代码块synchronized是一个封装体(带有同步特性),而函数add本身也是种封装,因此让函数具有“同步性”即可:
class Bank{
private int sum;
public synchronized void add(int num){
sum+=num;
System.out.println("name="+Thread.currentThread().getName()+"sum="+sum);
}
}
我们回过来看上面出现过的一个问题的代码(进行了一些修改):
class Demo implements Runnable{
private int num = 100;
//实现Runnable接口,覆盖run方法
public synchronized void run(){
while (true){
if (num>0){
try{
Thread.sleep(10);
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
}
会出现一个问题,同步的范围加大了,因为只有if语句之后的部分是需要同步的,而范围扩大到了run方法,导致一个线程进行run方法,其他线程无法进行,因此num–的操作完全由一个线程完成了。
正确的范围加同步:
class Demo implements Runnable{
private int num = 100;
//实现Runnable接口,覆盖run方法
public void run(){
while (true){
synchronized (this){
if (num>0){
try{
Thread.sleep(10);
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
}
}
或将同步部分提出来单独封装到一个方法中:
class Demo implements Runnable{
private int num = 100;
//实现Runnable接口,覆盖run方法
public void run(){
while (true){
show();
}
}
public synchorized show(){
if (num>0){
try{
Thread.sleep(10);
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
因此可以总结出同步函数的格式:
写法一:
public synchronized void method()
{
// todo
}
写法二:
public void method()
{
synchronized(this) {
// todo
}
}
写法一修饰的是一个方法,写法二修饰的是一个代码块,但写法一与写法二是等价的,都是锁定了整个方法时的内容。
同步函数所用的锁是this:同步函数仅仅是函数带有了同步性,同步synchronized本身是不带有锁的,因此函数是带有锁的,函数使用的时候是被对象调用的,函数都有自己所属的this,例如上述实例:
class Bank{
private int sum;
public void add(int num){
sum+=num;
System.out.println("sum="+sum);
}
}
class Cus implements Runnable{
Bank b = new Bank();//对象b是多个线程的共享数据
public synchronized void run(){
System.out.println("this:"+this);
for (int x=0;x<3;x++){
b.add(100);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Cus c = new Cus();
System.out.println("this:"+c);
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
对比hash值即可发现,同步函数使用的锁是this,因此保证各个线程使用的是相同的锁。
同步函数与同步代码块的区别:
- 同步函数的锁是固定的this,同步代码块的锁可以是任意的对象
- 同步代码块中使用的锁是this时可以简化为同步函数
静态同步函数
首先,静态函数本身不具有this,静态的同步函数使用的锁是该函数所属的字节码文件对象,可以用getClass方法获取,也可以使用“类名.class”表示(类的字节码文件是唯一的,只不过可以创建多个对象而已,如果是静态方法中,使用“类名.class”,因为getClass方法不是静态方法)
class SyncThread implements Runnable {
private static int count;
public SyncThread() {
count = 0;
}
public synchronized static void method() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void run() {
method();
}
}
调用代码:
SyncThread syncThread1 = new SyncThread();
SyncThread syncThread2 = new SyncThread();
Thread thread1 = new Thread(syncThread1, "SyncThread1");
Thread thread2 = new Thread(syncThread2, "SyncThread2");
thread1.start();
thread2.start();
结果:
SyncThread1:0
SyncThread1:1
SyncThread1:2
SyncThread1:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread2:7
SyncThread2:8
SyncThread2:9
syncThread1和syncThread2是SyncThread的两个对象,但在thread1和thread2并发执行时却保持了线程同步。这是因为run中调用了静态方法method,而静态方法是属于类的,所以syncThread1和syncThread2相当于用了同一把锁。这与Demo1是不同的。synchronized作用于一个类T时,是给这个类T加锁,T的所有对象用的是同一把锁。
synchorized注意事项
(1) synchronized关键字不能继承。
虽然可以使用synchronized来定义方法,但synchronized并不属于方法定义的一部分,因此,synchronized关键字不能被继承。如果在父类中的某个方法使用了synchronized关键字,而在子类中覆盖了这个方法,在子类中的这个方法默认情况下并不是同步的,而必须显式地在子类的这个方法中加上synchronized关键字才可以。当然,还可以在子类方法中调用父类中相应的方法,这样虽然子类中的方法不是同步的,但子类调用了父类的同步方法,因此,子类的方法也就相当于同步了。这两种方式的例子代码如下:
在子类方法中加上synchronized关键字:
class Parent {
public synchronized void method() { }
}
class Child extends Parent {
public synchronized void method() { }
}
在子类方法中调用父类的同步方法
class Parent {
public synchronized void method() { }
}
class Child extends Parent {
public void method() { super.method(); }
}
(2)在定义接口方法时不能使用synchronized关键字。
(3)构造方法不能使用synchronized关键字,但可以使用synchronized代码块来进行同步。
(4)一个线程进入一个对象的synchronized方法(非静态)时,其他线程是否可以进入此对象的其他方法?
这取决于其他方法本身,可以访问该对象的非synchronized方法或者静态synchronized方法,因为静态static方法用的同步锁是当前类的字节码,与非静态方法不能同步(非静态的方法的锁用的是this),因此两个方法不是用的同一个锁,因此静态方法可以被调用。
死锁
死锁的原因:同步的嵌套
class Demo implements Runnable{
private int num = 100;
public boolean flag = true;
private Object lock = new Object();
//实现Runnable接口,覆盖run方法
public void run(){
if (flag){
while (true){
synchronized (lock){
show();//持有锁lock,想进入锁是this的show方法
}
}
}else {
while (true){
show();//持有锁this,但是show方法中想要执行需要锁lock
}
}
}
public synchronized void show(){
synchronized (lock){
if (num>0){
try{
Thread.sleep(10);
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
}
public class SingleDemo {
public static void main(String[] args) {
Demo t = new Demo();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{
Thread.sleep(10);
}catch (InterruptedException e){
}
t.flag = false;
t2.start();
}
}