package com.wkcto.intrinsiclock;
/**
* 同步過程中線程出現異常, 會自動釋放鎖對象
*
* Author: 老崔
*/
public class Test09 {
public static void main(String[] args) {
//先創建Test01對象,通過對象名調用mm()方法
Test09 obj = new Test09();
//一個線程調用m1()方法
new Thread(new Runnable() {
@Override
public void run() {
obj.m1(); //使用的鎖對象是Test06.class
}
}).start();
//另一個線程調用sm2()方法
new Thread(new Runnable() {
@Override
public void run() {
Test09.sm2(); //使用的鎖對象是Test06.class
}
}).start();
}
//定義方法,打印100行字符串
public void m1(){
//使用當前類的運行時類對象作為鎖對象,可以簡單的理解為把Test06類的字節碼文件作為鎖對象
synchronized ( Test09.class ) {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + " --> " + i);
if ( i == 50){
Integer.parseInt("abc"); //把字符串轉換為int類型時,如果字符串不符合 數字格式會產生異常
}
}
}
}
//使用synchronized修飾靜態方法,同步靜態方法, 默認運行時類Test06.class作為鎖對象
public synchronized static void sm2(){
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + " --> " + i);
}
}
}