线程同步synchronized
synchronized只是保证在同一个时刻,其他线程不能访问锁定的资源,但是其他方法或者是变量不能锁定控制的
解决死锁办法之一:
1、将锁的粒度放粗一点(一口气锁住所有资源)
//模拟“锁住”重要资源不能在一段时间类被多个线程使用 public class TestThread implements Runnable{ TestSync testSync = new TestSync(); public static void main(String[] args) { TestThread thread = new TestThread(); Thread t1 = new Thread(thread); Thread t2 = new Thread(thread); Thread t3 = new Thread(thread); //设置线程的名字 t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); t3.start(); } @Override public void run() { testSync.add(Thread.currentThread().getName()); } } public class TestSync { private static int num = 0; //下面这个方法不能在同一时间段被多个线程调用 public synchronized void add(String name){ //下面是另外一种语法结构 // synchronized(this){ num++; try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("你是第" + num + "个使用"); // } } }
可以简单的模拟死锁的情况
public class TestDeadLockMain { public static void main(String[]args){ TestDeadLock t1 = new TestDeadLock(); TestDeadLock t2 = new TestDeadLock(); t1.setFlag(0); t2.setFlag(1); Thread thread1 = new Thread(t1); Thread thread2 = new Thread(t2); thread1.start(); thread2.start(); } } package hb.thread; public class TestDeadLock implements Runnable { public int flag = 1; public Object obj1 = new Object(); public Object obj2 = new Object(); public void setFlag(int flag){ this.flag = flag; } @Override public void run() { if(0 == flag){ synchronized(obj1){ try { System.out.println("flag = " + flag); Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(obj2){ System.out.println("second obj2"); } } } if(1 == flag){ synchronized(obj2){ try { System.out.println("flag = " + flag); Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(obj1){ System.out.println("second obj1"); } } } } }
回忆过去,珍惜现在,放眼未来