實例一、靜態方法的同步處理
public class DataCopyA {
public static void main(String[] args) {
task(0, 5*1000*1);
DataCopyB.task(0, 5 * 1000 * 1);
}
public static void task(long time, long time2) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
String str ="DataCopy-A";
//斷點打於此處,進入方法體就會阻塞DataCopy-B的輸出
DataCopyA.selectSql(str);
}
};
timer.schedule(task, time, time2);
}
protected synchronized static void selectSql(String str) {
System.out.println("--------------------");
System.out.println(Thread.currentThread());
System.out.println(str);
}
}
public class DataCopyB {
public static void task(long startTime, int time2) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
String str ="CopyData-B";
DataCopyA.selectSql(str);
}
};
timer.schedule(task, startTime, time2);
}
}
實例二、對同一對象的非靜態方法處理
public class DataCopyA {
private DataCopyA() {}
private static DataCopyA dataCopyA = new DataCopyA();
public static DataCopyA getInstance() {
return dataCopyA;
}
public static void main(String[] args) {
task(0, 5*1000*1);
DataCopyB.task(0, 5 * 1000 * 1);
}
public static void task(long time, long time2) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
String str ="DataCopy-A";
//斷點打於此處,進入方法體就會阻塞DataCopy-B的輸出
DataCopyA.getInstance().selectSql(str);
}
};
timer.schedule(task, time, time2);
}
protected synchronized void selectSql(String str) {
System.out.println("--------------------");
System.out.println(Thread.currentThread());
System.out.println(str);
}
}
public class DataCopyB {
public static void task(long startTime, int time2) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
String str ="CopyData-B";
DataCopyA.getInstance().selectSql(str);
}
};
timer.schedule(task, startTime, time2);
}
}