方法一
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
private Lock lock = new ReentrantLock();
private Condition numCondition = lock.newCondition();
private Condition strCondition = lock.newCondition();
public static void main(String[] args) {
TestLock lock = new TestLock();
Thread num = new Thread(lock.new PrintLockNum());
Thread str = new Thread(lock.new PrintLockStr());
num.start();
str.start();
}
class PrintLockNum implements Runnable {
@Override
public void run() {
for(int i=1;i<=26*2;i++) {
lock.lock();//通过创建 Condition 对象来使线程 wait,必须先执行 lock.lock 方法获得锁
strCondition.signalAll();//condition 对象的 signal 方法可以唤醒 wait 线程
System.out.print(i);
if(i%2 == 0) {
try {
numCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
}
class PrintLockStr implements Runnable {
@Override
public void run() {
for(int i=65;i<=26+64;i++) {
lock.lock();
numCondition.signalAll();
System.out.print((char) i);
try {
strCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
}
方法二
public class Test {
public static void main(String[] args) {
Object o = new Object();
Thread t1 = new Thread(new PrintNum(o));
Thread t2 = new Thread(new PrintStr(o));
t1.start();
t2.start();
}
}
class PrintNum implements Runnable {
private Object object;
PrintNum(Object object) {
this.object = object;
}
@Override
public void run() {
synchronized (object) {
for(int i=1;i<=26*2;i++) {
System.out.print(i);
if(i % 2 == 0) {
object.notifyAll();//先唤醒所有线程
try {
object.wait();//阻塞当前线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class PrintStr implements Runnable {
private Object object;
PrintStr(Object object) {
this.object = object;
}
@Override
public void run() {
synchronized (object) {
for(int i = 65;i<=65+26-1;i++) {//A 65 a 97 26个英文字母在a的后边有25个bcd...字符
System.out.print((char)i);
object.notifyAll();
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}