第一種 給方法前面 加 synchronizedjava
示例:class
public synchronized void out2(String name) { int length = name.length(); for (int i = 0; i < length; i++) { System.out.print(name.charAt(i)); } System.out.println(); }
第二種 在方法裏面加synchronized塊方法
示例:co
public void out(String name) { int length = name.length(); synchronized (Outputer.class) { for (int i = 0; i < length; i++) { System.out.print(name.charAt(i)); } System.out.println(); } }
第三種 sync
java.util.concurrent.locks.Locksynchronized
給代碼上鎖void
示例:
public void output(String name){ int len = name.length(); lock.lock(); try{ for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); }finally{ lock.unlock(); } }