// synchronized - 同步关键字
// 多个线程访问同步方法时,只能一个一个访问,同步操作
// new Hashtable<>();
// synchronized 关键字还可以修饰代码块,称之为同步代码块
/*
synchronized( 用于同步对象 ) {
处理逻辑
}
*/
Num num = new Num();
User user = new User(num);
user.start();
Bank bank = new Bank(num);
bank.start();
}
}
class Num {
}
class Bank extends Thread {
private Num num;
public Bank ( Num num ) {
this.num = num;
}
public void run () {
synchronized ( num ) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("9:00,开门,开始叫好");
num.notifyAll();
}
}
}
class User extends Thread {
// public synchronized void test() {
//
// }
private Num num;
public User ( Num num ) {
this.num = num;
}
public void run () {
synchronized ( num ) {
System.out.println("我是号码1,银行还没开门,我需要等一会");
try {
num.wait();
} catch ( InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("叫到我号了,该我办业务了。");
}
// 所谓线程安全问题,其实就是多个线程在并发执行时,修改了共享内存中共享对象的属性,导致的数据冲突问题
User7 user = new User7();
Thread t1 = new Thread(()->{
user.name = "zhangsan";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(user.name);
});
Thread t2 = new Thread(()->{
user.name = "lisi";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(user.name);
});
t1.start();
t2.start();
System.out.println("main线程执行完毕");
}
}
class User7 {
public String name;
}