public void noSync() {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 多线程执行 同一实例的 同一个不带锁方法,乱序执行
*/
@Test
public void noSyncTest() throws InterruptedException {
SyncObject obj = new SyncObject();
new Thread(() -> obj.noSync()).start();
new Thread(() -> obj.noSync()).start();
//当前线程等待测试线程执行完成
TimeUnit.SECONDS.sleep(3);
}
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
public void thisSync() {
synchronized (this) {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 多线程执行 同一实例的 同一个带this锁方法,顺序执行
*/
@Test
public void thisSyncTest() throws InterruptedException {
SyncObject obj = new SyncObject();
new Thread(() -> obj.thisSync()).start();
new Thread(() -> obj.thisSync()).start();
//当前线程等待线程t1和t2执行完成
Thread.sleep(3000);
}
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
/**
* 多线程执行 不同实例的 同一个带锁的方法,乱序执行
*/
@Test
public void thisSync2Test() throws InterruptedException {
SyncObject x = new SyncObject();
SyncObject y = new SyncObject();
new Thread(() -> x.thisSync())