- synchronized版本
调用
public class Main {
public static void main(String[] args) throws InterruptedException {
Num1 num1 = new Num1();
new Thread1(num1).start();
new Thread2(num1).start();
}
}
目标类
public class Num1 {
private boolean flag = true;
public synchronized void printNum() throws InterruptedException{
int i = 1;
while(i<53){
if (flag) {
System.out.print(i);
if (i%2==0) {
flag=false;
notifyAll();
}
i++;
}else {
wait();
}
}
}
public synchronized void printWord() throws InterruptedException{
char a='A';
int i=0;
while(i!=26){
if (!flag) {
System.out.print(a++);
flag=true;
notifyAll();
i++;
}else {
wait();
}
}
}
}
Thread1打印数字
public class Thread1 extends Thread {
private Num1 num1;
public Thread1(Num1 num1){
this.num1 = num1;
}
public void run() {
try {
num1.printNum();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thread1打印字母
public class Thread2 extends Thread {
private Num1 num1;
public Thread2(Num1 num1){
this.num1 = num1;
}
public void run() {
try {
num1.printWord();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
- Lock版本
需要用到 Lock 和 Condition,用Lock锁,Condition进行线程间通信,代码其实是一样的,填到该模板下就行
public void printNum() throws InterruptedException{
lock.lock();
try {
int i = 1;
while(i<53){
if (flag) {
System.out.print(i);
if (i%2==0) {
flag=false;
condition.signalAll();
}
i++;
}else {
condition.await();
}
}
} finally {
lock.unlock();
}
}