一、内置锁
- 同步:synchronized
- 协作:Object # wait/notify/notifyAll
public class PrintNumber {
/**
* 打印锁,同一时刻仅有一个任务可以持有此锁
*/
private static Object lock = new Object();
/**
* 计数器
*/
private static int counter = 1;
/**
* 计数器最大值
*/
private static final int MAX_COUNTER = 100;
public static void main(String args[]) {
// 奇数打印线程
Thread oddThread = new Thread() {
@Override
public void run() {
// 请求打印锁
synchronized (lock) {
while (counter <= MAX_COUNTER) {
// counter为奇数,打印counter并唤醒偶数打印线程
if (counter % 2 != 0) {
System.out.println("Thread1 : " + counter);
counter = counter + 1;
lock.notifyAll();