/**
-
同步线程
*/
class SyncThread implements Runnable {
private static int count;public SyncThread() {
count = 0;
}public void run() {
synchronized(this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + “:” + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}public int getCount() {
return count;
}
}
调用SyncThread的方法:
SyncThread syncThread = new SyncThread();
Thread thread1 = new Thread(syncThread, “SyncThread1”);
Thread thread2 = new Thread(syncThread, “SyncThread2”);
thread1.start();
thread2.start();
运行结果:
SyncThread1:0
SyncThread1:1
SyncThread1:2
SyncThread1:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread2:7
SyncThread2:8
SyncThread2:9*