```添加演示同步方法的用法以防止实例化
新增的syn类演示了同步方法的用法,以防止在多线程环境中实例化。这通过尝试获取对象锁并打印对象引用的getLock方法以及调用wait的printSyn方法进行演示。 ```
This commit is contained in:
parent
ddcf0f3888
commit
30db149f1a
@ -45,7 +45,46 @@ public class LeetCode343 {
|
||||
static Object o = new Object();
|
||||
static int count = 0;
|
||||
|
||||
static class syn{
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
syn syn = new syn();
|
||||
// 创建一个线程来调用 printSyn 方法
|
||||
Thread thread1 = new Thread(() -> {
|
||||
try {
|
||||
syn.printSyn();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
// 创建另一个线程来调用 getLock 方法
|
||||
Thread thread2 = new Thread(() -> {
|
||||
syn.getLock();
|
||||
});
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
}
|
||||
|
||||
public synchronized void printSyn() throws InterruptedException {
|
||||
Thread.sleep(1000); // 睡眠,看this是不是被其他线程拿走了
|
||||
// 睡眠的过程中拿着this,下面的this不能拿到
|
||||
this.wait(); // 卡在这
|
||||
System.out.println("syn");
|
||||
}
|
||||
|
||||
// 另一个线程尝试去获取this对象
|
||||
public synchronized void getLock() {
|
||||
System.out.println(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int a = 100;
|
||||
long b = 100L;
|
||||
System.out.println(a==b);
|
||||
|
||||
float c = 1.0f;
|
||||
int d = 1;
|
||||
System.out.println(c==d);
|
||||
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
|
Loading…
Reference in New Issue
Block a user