代码段:
public class SyncTest {
public static void main(String[] args) {
new SyncTest().test();
}
private void test() {
final Outputer outputer = new Outputer();
// Thread 1
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.outPut("一二三四五六七八九");
}
}
}).start();
// Thread2
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Outputer.outPut2("123456789");
}
}
}).start();
}
static class Outputer {
public void outPut( String name) {
int len = name.length();
synchronized (Outputer.this) { // lock is Outputer.class
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public static synchronized void outPut3( String name) { // lock also is Outputer.class
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
输出:
123456789 1一2二三四五六七八九 3456789
显然没有同步,请伸出手,谢谢答案 0 :(得分:0)
您需要指定类实例而不是this
,因此两者都使用相同的Monitor对象
static class Outputer {
public void outPut( String name) {
int len = name.length();
synchronized (Outputer.class) { // Outputer.this is not the same as Outputer.class
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
或者你可以使用一个单独的监视器对象,以便明确使用它:
static class Outputer {
private static Object syncronisationMonitor = new Object();
// nonstatic method
public void outPut( String name) {
synchronized (syncronisationMonitor ) { // we use the same monitor as in the static method
[...]
}
}
//static method
public static void outPut3( String name) {
synchronized (syncronisationMonitor ) { // we use the same monitor as in the non-static method
[...]
}
}
}