现在的位置: 首页 > 综合 > 正文

43、多线程同步及synchronized关键字

2018年01月26日 ⁄ 综合 ⁄ 共 5869字 ⁄ 字号 评论关闭

为什么要引入同步机制
      在多线程环境中,可能会有两个甚至更多的线程试图同时访问一个有限的资源。必须对这种潜在资源冲突进行预防。
      解决方法:在线程使用一个资源时为其加锁即可。访问资源的第一个线程为其加上锁以后,其他线程便不能再使用那个资源,除非被解锁。

public class FetchMoney
{
	public static void main(String[] args)
	{
		Bank bank = new Bank();
		Thread t1 = new MoneyThread(bank);//柜台
		Thread t2 = new MoneyThread(bank);//取款机
	
		t1.start();
		t2.start();
	}
	
}
class Bank
{
	private int money = 1000;
	
//	public synchronized int getMoney(int number)
	public  int getMoney(int number)
	{
		if(0>number)
		{
			return -1;
		}
		else if(money < number)
		{
			return -2;
		}
		else if(money < 0)
		{
			return -3;
		}
		
		else
		{
			try
			{
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			money -= number;
			System.out.println("left money:"+ money);
			return number;
		}
	}
}
class MoneyThread extends Thread
{
	private Bank bank;
	
	public MoneyThread(Bank bank)
	{
		this.bank = bank;
	}
	@Override
	public void run()
	{
		System.out.println(bank.getMoney(800));
	}
}

这个程序运行,对于银行一个账户1000元,有可能两次都取出800,剩余-600,也可能两次都取800,剩余200,结果明显不对,这是因为对getMoney(int money)这个方法的线程级访问无法控制造成的。如果方法的声明中加上synchronized关键字,就可以得到解决

1、synchronized关键字:当synchronized关键字修饰一个方法的时候,该方法叫做同步方法。     

      java中的每个对象都有一个锁(lock)或者叫做监视器(monitor),当访问某个对象的synchronized方法时,表示该对象上锁,,此时其他任何线程都无法再去访问该synchronized方法了,直到之前的那个线程执行方法完毕后(或者是抛出了异常),那么将该对象的锁释放掉,其他线程才有可能再去访问该synchronized方法

2、

public class ThreadTest4
{
	public static void main(String[] args)
	{
		Example example = new Example();
		Thread t1 = new TheThread(example);
		Thread t2 = new TheThread2(example);
		
		t1.start();
		t2.start();
	}
}
class Example
{
	public synchronized void excute()
	{
		for(int i = 0;i<20;i++)
		{
			try
			{
				Thread.sleep(200);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("example1:"+i);
		}
	}
	
	public synchronized void excute2()
	{
		for(int i = 0;i<20;i++)
		{
			try
			{
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("example2:"+i);
		}
	}
}
class TheThread extends Thread
{
	private Example example;
	public TheThread(Example example)
	{
		this.example = example;
	}
	public void run()
	{
		this.example.excute();
	}
}
class TheThread2 extends Thread
{
	private Example example;
	public TheThread2(Example example)
	{
		this.example = example;
	}
	public void run()
	{
		this.example.excute2();
	}
}

将顺序打印,先excute1:0-19,然后excute2:0-19

 如果一个对象有多个synchronized方法,某一时刻某个线程已经进入到了某个synchronized方法,那么在该方法没有执行完毕前,其他线程是无法访问该对象的任何synchronized方法的。

如果将main()主方法改为:

public static void main(String[] args)
	{
		Example example = new Example();
		Thread t1 = new TheThread(example);
		example = new Example();
		Thread t2 = new TheThread2(example);
		
		t1.start();
		t2.start();
	}

将乱序。

如果将Example的两个方法都加上static关键字,这样定义

public synchronized static void excute()

public synchronized static void excute2()

则将顺序打印

如果第一个的static去掉,即一个是非静态的,一个是静态的,则乱序

      如果某个synchronized方法是static的,那么当线程访问该方法时,他锁定的并不是synchronized方法所在的对象,而是synchronized方法所在的对象所对应的Class对象,因为java中无论一个类有多少个对象,这些对象会对应唯一一个class对象,因此当线程分别访问同一个类的两个对象的两个static,synchronized方法时,他们的执行顺序也是顺序的,也就是说一个线程先去执行方法,执行完毕后另一个线程才开始执行。

3、synchronized的代码块

class Example
{
	public  void excute()
	{
		Object obj = new Object();
		synchronized (obj){          //synchronized代码块定义
		for(int i = 0;i<20;i++)
		{
			try
			{
				Thread.sleep(200);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("example1:"+i);
		}
		}
	}
	
	public synchronized static void excute2()
	{
		for(int i = 0;i<20;i++)
		{
			try
			{
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("example2:"+i);
		}
	}
}

 

synchronized块,写法:

synchronized(object)

{

}

表示线程在执行的时候会对obj对象上锁。

这相当于定义了一个标志,用这个标志是否上锁来控制代码块的执行,如果将obj换为this,就是对Example对象的锁定,相当于在方法上的synchronized声明。

synchronized方法是一种粗粒度的并发控制,某一时刻,只能有一个线程执行该synchronized方法;synchronized块则是一种细粒度的并发控制,只会将块中的代码同步,位于方法内、synchronized块之外的代码是可以被多个线程同时访问到的。

 当synchronized方法执行完或发生异常时,会自动释放锁。被synchronized保护的数据应该是私有(private)的。

4、怎样实现同步:线程间的相互作用:

死锁(dead lock)

Object类的wait 和 notify方法:

wait方法将释放对象锁,然后等待另一个线程调用这个对象的notify()或notifyAll()方法来唤醒方法,唤醒后不是立即继续执行,而是先获得对象锁,获得后在执行。

具有wait()和notify()的线程状态图:

 

5、举例:对一个对象Sample中的成员变量进行增减操作,使结果为0和1交互出现。

public class Sample
{
	private int number;
	
	public synchronized void inCrease()
	{
		if(0 != number)
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		
		number++;
		System.out.println(number);
		notify();
	}
	
	public synchronized void deCrease()
	{
		if( 0 == number)
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		
		number--;
		System.out.println(number);
		notify();
	}
}


public class IncreaseThread extends Thread
{
	private Sample sample;
	
	public IncreaseThread(Sample sample)
	{
		this.sample = sample;
	}
	
	@Override
	public void run()
	{
		for(int i = 0; i < 10; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			sample.inCrease();
		}		
	}
}


public class DecreaseThread extends Thread
{
	private Sample sample;
	
	public DecreaseThread(Sample sample)
	{
		this.sample = sample;
	}
	
	@Override
	public void run()
	{
		for(int i = 0; i < 10; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			sample.deCrease();
		}		
	}
}


public class MainTest
{
	public static void main(String[] args)
	{
		Sample sample = new Sample();
		
		Thread t1 = new IncreaseThread(sample);
		Thread t2 = new DecreaseThread(sample);
		
		t1.start();
		t2.start();
	}
}

对于两个线程,像上面的程序,结果正确,如果再增加几个线程,如:

public class MainTest
{
	public static void main(String[] args)
	{
		Sample sample = new Sample();
		
		Thread t1 = new IncreaseThread(sample);
		Thread t2 = new DecreaseThread(sample);
		Thread t3 = new IncreaseThread(sample);
		Thread t4 = new DecreaseThread(sample);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

结果错误,出现的原因一种可能是因为当number为0时,进入inCrease方法,当判断number为0,要执行number++时,执行了线程切换,切换到另一个线程,这个线程也执行inCrease方法,因为这时number为0,所以执行了number++,这时number为1,线程执行完毕,调用notify(),结果又唤醒了原来的inCrease线程,原线程接着wait()之后执行,执行number++操作,导致number变为2,出现错误,具体解决方法就是在线程唤醒后,应该再次检查number的值进行判断,所以将if判断改为while判断:

public class Sample
{
	private int number;
	
	public synchronized void inCrease()
	{
		while(0 != number)        //改为while
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		
		number++;
		System.out.println(number);
		notify();
	}
	
	public synchronized void deCrease()
	{
		while( 0 == number)        //改为while
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		
		number--;
		System.out.println(number);
		notify();
	}
}

 

      wait与notify方法都是定义在Object类中,而且是final的,因此会被所有的java类所继承并且无法重写。这两个方法要求在调用时线程应该已经获得了对象的锁,因此对这两个方法的调用需要放在synchronized方法或块当中。当线程执行了wait方法时,它会释放掉对象的锁。

6、Thread类的sleep方法:另一个会导致线程暂停的方法就是Thread类的sleep方法,它会导致线程睡眠指定的毫秒数,但线程在睡眠的过程中是不会释放掉对象的锁的。

抱歉!评论已关闭.