一次简单的java多线程demo
直接上代码`:
public class PrintABC {
public static void main(String[] args) throws InterruptedException {
Printer p1 = new Printer();
PrintA pa = new PrintA(p1);
PrintB pb = new PrintB(p1);
PrintC pc = new PrintC(p1);
new Thread(pa,"A").start();
new Thread(pb,"B").start();
new Thread(pc,"C").start();
}
}
class Printer{
private int num = 1;
public void printA(){
for(int j = 0;j < 2;j++){
synchronized(this){
System.out.println("开始判断进入 A ");
while( num != 1){
try {
System.out.println("A 开始等待");
this.wait();
System.out.println("A 结束等待");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 3; i++) {//表示 打印3次
System.out.print("A");
}
System.out.println();
num = 2;
this.notifyAll();
}
}
}
public void printB(){
for(int j = 0; j < 2 ; j++){
synchronized (this){
System.out.println("开始判断进入 B ");
while(num != 2){
try {
System.out.println("B 开始等待");
this.wait();
System.out.println("B 结束等待");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = 3;
for (int i = 0; i < 3; i++) {//表示 打印3次
System.out.print("B");
}
System.out.println();
this.notifyAll();
}
}
}
public void printC(){
for(int j = 0; j < 2; j++){
synchronized (this){
System.out.println("开始判断进入 C");
while(num != 3){
try {
System.out.println("C 开始等待");
this.wait();
System.out.println("C 结束等待");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = 1;
for (int i = 0; i < 3; i++) {//表示 打印3次
System.out.print("C");
}
System.out.println();
this.notifyAll();
}
}
}
}
class PrintA implements Runnable{
private Printer p1;
public PrintA(Printer p1) {
this.p1 = p1;
}
@Override
public void run() {
p1.printA();
}
}
class PrintB implements Runnable{
private Printer p1;
public PrintB(Printer p1) {
this.p1 = p1;
}
@Override
public void run() {
p1.printB();
}
}
class PrintC implements Runnable{
private Printer p1;
public PrintC(Printer p1) {
this.p1 = p1;
}
@Override
public void run() {
p1.printC();
}
}
然后放上运行结果:
首先发现,如果打印完 A ,然后会再输出语句之后有个this.notifyAll()方法,然后看到输出语句 AAA后面总会有 开始判断进入 A 输出,
BBB 后面也有 开始判断进入 B,以为会优先唤醒本身当前线程,但是后来多运行几次,发现并不是这样,还是随机的。
每一个睡眠语句都是这样的:
System.out.println("C 开始等待");
this.wait();
System.out.println("C 结束等待");
当AAA输出完毕之后,调用notifyAll()方法,也会在前或者在后进入A的while条件判断,会输出 A 开始等待,
当条件满足B 的输出语句(输出 AAA BBB CCC 为正常输出),输出完BBB 之后,调用notifyAll()方法会发现,可能会输出
A 结束等待 和 A开始等待,
我想,唤醒的时候就是调用wait之后的语句嘛?然后再走一遍循环。