java线程同步
这次写一个多线程的demo,用生活中的例子来讲,妈妈要做饭,打开冰箱一看,菜和米都没有了。于是让我去买菜,让爸爸去买米。我去买菜和爸爸去买米是并发执行的,互相不干涉。但是妈妈没有米和菜式没法做饭的,所以等着米和菜把饭做好。代码如下:
public class threadDemo { /** * @param args */ private static Object lock = new Object(); public static void main(String[] args) { // TODO Auto-generated method stub Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { System.out.println("妈妈去做饭,发现没有菜和米,让我去买菜,爸爸去买米"); try { lock.wait(); lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("妈妈把做饭做好"); } } }); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { System.out.println("我去买菜..."); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("把菜给妈妈"); lock.notify(); } } }); t2.start(); Thread t3 = new Thread(new Runnable() { @Override public void run() { System.out.println("爸爸去买米..."); synchronized (lock) { try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("把米给妈妈"); lock.notify(); } } }); t3.start(); } }
效果:
妈妈去做饭,发现没有菜和米,让我去买菜,爸爸去买米
我去买菜...
爸爸去买米...
把菜给妈妈
把米给妈妈
妈妈把做饭做好