GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — JavaInterview/java/src/JavaBasic/Synch.java at master · damaohongtu/JavaInterview Expand file tree/ Copy pathSynch.javaMore file actions 90 lines (75 loc) · 2 KB / Copy pathSynch.javaFile metadata and controls90 lines (75 loc) · 2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 package JavaBasic;/** * @Classname Synch * @Description 对于同步的理解 * @Date 19-5-25 下午1:57 * @Created by mao<[email protected]> */ class Callme{ // synchronized void call(String msg){ void call(String msg){ System.out.print("["+msg); try{ Thread.sleep(1000); }catch (InterruptedException e){ System.out.println("Interrupted"); } System.out.println("]"); } //假设这是第二方的代码,不能使用synchronized关键字修饰 } class Caller implements Runnable{ String msg; Callme target; Thread t; public Caller(Callme tar,String s){ target=tar; msg=s; t=new Thread(this); t.start(); } public void run(){ target.call(msg); } } class Caller_2 implements Runnable{ String msg; Callme target; Thread t; public Caller_2(Callme tar,String s){ target=tar; msg=s; t=new Thread(this); t.start(); } public void run(){ synchronized (target){ target.call(msg); } } } public class Synch { public static void main(String[] args){ Callme target=new Callme(); //没有组织三个线程同时调用同一个对象的同一个方法,在call前面加上synchronized关键字 Caller ob1=new Caller(target,"hello"); Caller ob2=new Caller(target,"synchronized"); Caller ob3=new Caller(target,"world"); try { ob1.t.join(); ob2.t.join(); ob3.t.join(); }catch (InterruptedException e){ System.out.println("interrupted"); } Caller_2 ob11=new Caller_2(target,"hello"); Caller_2 ob22=new Caller_2(target,"synchronized"); Caller_2 ob33=new Caller_2(target,"world"); try { ob11.t.join(); ob22.t.join(); ob33.t.join(); }catch (InterruptedException e){ System.out.println("interrupted"); } } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |