方法一:采用synchronized和wait()、notify()方法实现
package printNum01;
class Print{
boolean flag = true;//为了实现交替打印设置flag
public synchronized void printNum(int i) {
if (flag == false) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(2*i-1);//连着打印两个数字
System.out.print(2*i);
flag = false;//将flag置为false
notify();//通知alpha线程
}
public synchronized void printAlpha(int i) {
if (flag == true) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print((char)(i+'A'));//打印字母
flag = true;//将flag置为true
notify();//通知alpha线程
}
}
//数字类
class Num extends Thread {
private Print p;
public Num(Print p) {
this.p = p;
}
@Override
public void run() {
for (int i = 1; i <= 26; i++) {
p.printNum(i);
}
}
}
//字母类
class Alphabet extends Thread {
private Print p;
public Alphabet(Print p) {
this.p = p;
}
@Override
public void run() {
for (int j = 0; j <26 ; j++) {
p.printAlpha(j);
}
}
}
public class PrintNum01 {
public static void main(String[] args) {
Print p = new Print();
Num num = new Num(p);
Alphabet alphabet = new Alphabet(p);
num.start();
alphabet.start();
}
}
运行结果:
方法二:采用Lock和lock()、unlock()方法实现
package printNum02;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Print {
boolean flag = true;//为了实现交替打印设置flag
Lock lock = new ReentrantLock();//引入lock
Condition NumCondition = lock.newCondition();//创建数字等待队列
Condition AlphabetCondition = lock.newCondition();//创建字母等待队列
public void printNum(int i) {
lock.lock();//上锁
try {
if (flag == false) {
try {
//wait();
NumCondition.await();//Num线程阻塞,Num进入等待队列中
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//注意这里不能用else,因为当wait()被唤醒时会沿着wait()之后的代码执行,放在else中就不能被执行了(下同)
System.out.print(2 * i - 1);//连着打印两个数字
System.out.print(2 * i);
flag = false;//将flag置为false
//notify();//通知alpha线程
AlphabetCondition.signal();
} finally {
lock.unlock();//解锁
}
}
public void printAlpha(int i) {
lock.lock();//上锁
try {
if (flag == true) {
try {
//wait();
AlphabetCondition.await();//Alpha线程阻塞,Alpha进入等待队列中
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print((char) (i + 'A'));//打印字母
flag = true;//将flag置为true
//notify();//通知Num线程
NumCondition.signal();
} finally {
lock.unlock();//解锁
}
}
}
//数字类
class Num extends Thread {
private Print p;
public Num(Print p) {
this.p = p;
}
@Override
public void run() {
for (int i = 1; i <= 26; i++) {
p.printNum(i);
}
}
}
//字母类
class Alphabet extends Thread {
private Print p;
public Alphabet(Print p) {
this.p = p;
}
@Override
public void run() {
for (int j = 0; j < 26; j++) {
p.printAlpha(j);
}
}
}
public class PrintNum02 {
public static void main(String[] args) {
Print p = new Print();
Num num = new Num(p);
Alphabet alphabet = new Alphabet(p);
num.start();
alphabet.start();
}
}
运行结果: