使用synchronized
public void demo1() {
final Object o = new Object();
char[] arr1 = "123456".toCharArray();
char[] arr2 = "ABCDEF".toCharArray();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o) {
for (char c: arr1) {
System.out.print(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o) {
for (char c: arr2) {
System.out.print(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
}
});
t1.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
使用Lock
public void demo2() {
char[] arr1 = "123456".toCharArray();
char[] arr2 = "ABCDEF".toCharArray();
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
for (char c: arr1) {
System.out.println(c);
// 调用该方法将线程从等待队列移动到阻塞队列里,然后再去获取锁
condition2.signal();
// 该方法会释放当前线程所占用的锁
condition1.await();
}
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
for (char c: arr2) {
System.out.println(c);
condition1.signal();
condition2.await();
}
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
t1.start();
t2.start();
}
如果你想了解更多我对编程和人生的思考,请关注公众号:青云学斋