java 同步方法的使用 防止多線程同時執行方法
/**
- java 同步方法的使用,防止多線程同時執行方法。
- synchronized方法加鎖,不管哪一個線程運行到這個方法時,都要檢查有沒有其它線程正在用這個方法,
有的話要等正在使用synchronized方法的線程運行完這個方法后再運行此線程,沒有的話,直接運行。 */ class Callme { synchronized void call(String msg) {
System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("]");
} }
class caller implements Runnable { String msg; Callme target;
public caller(Callme t, String s) {
target = t;
msg = s;
}
public void run() {
target.call(msg);
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
new caller(target, "Hello").run();
new caller(target, "Synchronized").run();
new caller(target, "World").run();
}
}</pre>
本文由用戶 123bt 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!