使用synchronized关键字可实现线程的互斥功能,即在此关键字包围的代码块中逻辑必须都执行完后才能再次此块,就像加了一把锁,执行到此块后此块就被锁住,其他逻辑不能再调用。但要实现同步必须对同一个对象加锁,否则无效。如:
public class Synchronized {
public static void main(String[] args) {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.output("ThreadA");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.output("ThreadB");
}
}
}).start();
}
static class Outputer {
public static synchronized void output1(String arg) {
for (int i = 0; i < arg.length(); i++) {
System.out.print(arg.charAt(i));
}
System.out.println();
}
public void output2(String arg) {
synchronized (this) {
for (int i = 0; i < arg.length(); i++) {
System.out.print(arg.charAt(i));
}
System.out.println();
}
}
public void output3(String arg) {
synchronized (Synchronized.class) {
for (int i = 0; i < arg.length(); i++) {
System.out.print(arg.charAt(i));
}
System.out.println();
}
}
public void output4(String arg) {
synchronized (arg) {
for (int i = 0; i < arg.length(); i++) {
System.out.print(arg.charAt(i));
}
System.out.println();
}
}
}
}
在主线程中新开两个线程,如果调用Outputer类中的output4方法打印,则无法同步,因为两个arg参数不是通个对象。
第一个和第三个方法可实现同步,因为都是给Outputer这个类本身加锁。
如下两个方法也可实现互斥同步,因为都是对Outputer类的实例对象加锁:
public synchronized void output(String arg) {
for (int i = 0; i < arg.length(); i++) {
System.out.print(arg.charAt(i));
}
System.out.println();
}
public void output2(String arg) {
synchronized (this) {
for (int i = 0; i < arg.length(); i++) {
System.out.print(arg.charAt(i));
}
System.out.println();
}
}