同步方法及同步块
synchronized方法和synchronized块
public synchronized void method(int args){};
synchronized方法控制对“对象”的访问,每一个对象对应一把锁,需要用synchronized方法调用该方法的对象的锁才能执行;一旦执行,就会独占;
锁的对象得是变化的量;
package ThreadThree; public class TicketUnsafe { public static void main(String[] args) { tickettt t=new tickettt(); new Thread(t,"小明").start(); new Thread(t,"小红").start(); new Thread(t,"黄牛").start(); } } class tickettt implements Runnable { private int ticket=20; boolean stoping=true; @Override public void run() { while (stoping){ buy(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void buy(){ if(ticket<=0){ stoping=false; return; } System.out.println(Thread.currentThread().getName()+ticket--); } }
死锁
多个线程各自占有一些共享的资源,而相互等待其他线程占有的资源才能运行,相互等待而停止执行;
public class DeadLock { public static void main(String[] args) { swap s1=new swap(1,"小张"); swap s2=new swap(2,"小李"); s1.start(); s2.start(); } } class money{ } class thing{ } class swap extends Thread { static money m1 = new money(); static thing t1 = new thing(); String name; int buy; swap(int buy, String name) { this.buy = buy; this.name = name; } public void run() { try { swap(); } catch (InterruptedException e) { e.printStackTrace(); } } public void swap() throws InterruptedException { if (buy == 1) { synchronized (m1) { System.out.println(this.name + "获得钱的锁"); Thread.sleep(100); } synchronized (t1) { System.out.println(this.name + "获得东西的锁"); } } else { synchronized (t1) { System.out.println(this.name + "获得东西的锁"); Thread.sleep(300); } synchronized (m1) { System.out.println(this.name + "获得钱的锁"); } } } }
1、一个资源只能被一个进程使用;
2、一个进程请求资源堵塞的时候,会对已获得的资源保持不放;
3、不剥夺,在进程使用完之前不能强行剥夺;
4、若干个进程形成一种首尾相接等待资源的情况;
Lock锁
ReentranLock类可重复锁;拥有和synchronized相同的并发性;