First question:class car extends thread{ private string name; private locked lock; public car (String name,Locked lock) { this.name = name; this.lock = lock; } Public void run () { synchronized (lock) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Car number:" + name + ", start into the tunnel ..."); for (int i=1;i <=10;i++) { try{ system.out.println ("Enter tunnel section" + i + "SEC"); thread.sleep (1000*1); }catch (Exception e) {}; } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Car number:" + name + ", End into tunnel ..."); } }}class Locked{ //empty Lock ...} Class cardemo{ public static void main (String[] args) { locked lock = new locked (); car car001 = new car ("car001", lock); &Nbsp; car car002 = new car ("car002", lock); car car003 = new car ("car003", lock); Car car004 = new car ("car004", lock); car car005 = new car ("car005", lock); car001.start (); car002.start (); car003.start (); Car004.start (); car005.start (); }} The second question:import java.util.arraylist;import java.util.list;class bee extends thread{ private String name; private List<Integer> list; private&Nbsp;int i = 1; public bee (string name,list<integer> list) { this.name = name; this.list = list; } Public void run () { while (true) { synchronized (list) { if (List.size () >= 10) { try{ list.wait(); }catch (exception e) {}; }else{ try{ thread.sleep ( ; ) }catch (exception e) {}; system.out.println ("Bee Number:" + name + ", Production section" + i + "Times honey! "); &nBsp; list.add (New integer (i)); i ++; list.notify (); } } } }}class bear extends thread{ private string name; private list <Integer> list; private int total = 1; private locked lock; public bear (string name,list<integer> list) { this.name = name; this.list = list; } public void Run () { while (true) { synchronized (list) { if (List.size () >= 10) { system.out.println ("Bear consumption:" + total + "Times! "); total ++; &nbSp; list.removeall (list); try{ thread.sleep (; ) }catch (exception e) {}; list.notify (); }else{ try{ &nBsp;list.wait (); }catch (exception e) { e.printstacktrace (); } } } } }}class ProductDemo{ public static Void main (String[] args) { list<integer> List = new arraylist<integer> (); bee Bee001 = nEw bee ("001", list); bee bee002 = new Bee ("002", list); bee bee003 = new bee ("003" , list); bee001.start (); bee002.start (); bee003.start (); bear bear = new bear ("001", list); bear.start (); }}
This article is from the "Forest Sensitive" blog, please be sure to keep this source http://senlinmin.blog.51cto.com/6400386/1773149
Big Data Java Foundation Eighth day job