測試一:
public class ThreadSynchronized {
/**
* 由於三個線程之間沒有同步,所以會出現打印錯誤的狀況
* @param args
*/
public static void main(String[] args) {
final Activity a = new Activity();
for (int i = 0; i < 3; i++) {
new Thread(){
public void run(){
for (int i = 0; i < 20; i++) {
a.output1("zhangjin");
}
}
}.start();
}
}
}
class Activity {
public void output1(String info){
for (int i = 0; i < info.length(); i++) {
System.out.print(info.charAt(i));
}
System.out.println();
}
}
實現同步的方法:
1、同步代碼塊
public void output1(String info){
//鎖對象
synchronized(this){
for (int i = 0; i < info.length(); i++) {
System.out.print(info.charAt(i));
}
System.out.println();
}
}
2、同步方法(鎖的是this對象)
public synchronized void output1(String info){
//同步代碼塊,鎖對象
for (int i = 0; i < info.length(); i++) {
System.out.print(info.charAt(i));
}
System.out.println();
}
3、非靜態同步方法與靜態同步方法之間保持同步測試
public class ThreadSynchronized {
/**
* 由於靜態同步方法output2()鎖住的是Activity.class(字節碼),
* 而非靜態同步方法output1()鎖住的是this對象,所以兩者之間不能保持同步
* @param args
*/
public static void main(String[] args) {
final Activity a = new Activity();
for (int i = 0; i < 3; i++) {
final int temp = i ;
new Thread(){
public void run(){
if(temp == 2){
for (int i = 0; i < 20; i++) {
a.output2("xiaoming");
}
}else{
for (int i = 0; i < 20; i++) {
a.output1("zhangjin");
}
}
}
}.start();
}
}
}
class Activity {
public synchronized static void output2(String info){
for (int i = 0; i < info.length(); i++) {
System.out.print(info.charAt(i));
}
System.out.println();
}
public synchronized void output1(String info){
for (int i = 0; i < info.length(); i++) {
System.out.print(info.charAt(i));
}
System.out.println();
}
所以,想要和靜態同步方法保持同步的話,我們需要使用同步代碼塊,而不能使用同步方法
如講output1更改為
public void output1(String info){
synchronized (Activity.class) {
for (int i = 0; i < info.length(); i++) {
System.out.print(info.charAt(i));
}
System.out.println();
}
}
即可。