测试一:
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();
}
}即可。