一、Sysnchronized简介
Sysnchronized:能够保证在同一时刻最多只有一个线程执行该段代码
创建线程的两种方法:
- 继承Thread类
- 实现Runnable接口
thread1.join()方法:等待线程1执行完后才接着执行
二、Sysnchronized两种用法(对象锁和类锁)
- 对象锁
包括方法锁(默认锁对象为this当前实例对象)和同步代码块锁(自己指定锁对象)
第一种:同步代码块锁(自己指定锁对象)
public class SynchronizedObject implements Runnable {
static SynchronizedObject instance = new SynchronizedObject();
@Override
public void run() {
synchronized (this) {
System.out.println("我是对象锁的代码块形式。我叫" +
Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "运行结束");
}
}
public static void main(String[] args) {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
while(t1.isAlive() || t2.isAlive()) {
}
}