java多线程——线程通信 sychronized 同步代码块。 使用 wait() , notifyAll().方法实现 两个线程输出12A34B56C78D......的效果。1~52 A~Z .
wait() 使当前线程沉睡
notifyAll() 唤醒所有沉睡的线程
主要注意点 sychronized 同步代码块 需要确定wait(),notifyAll的对象。
package test02;
public class Test {
public static void main(String[] args) {
Print p = new Print();
new MyThread01(p).start(); //线程1
new MyThread02(p).start(); //线程2
}
}
class Print { //用来确定输出
public int i = 1;
public char s = 'A';
public boolean flag = true;
}
class MyThread01 extends Thread { //输出数字
private Print p;
public MyThread01() {
};
public MyThread01(Print p) {
this.p = p;
}
public void run() {
synchronized (p) {
while (p.i <= 52) {
if (p.flag) {
System.out.print(p.i++);
if (p.i % 2 == 1) {
p.flag = false;
p.notifyAll();
}
} else {
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class MyThread02 extends Thread { //输出字母
private Print p;
public MyThread02() {
};
public MyThread02(Print p) {
this.p = p;
}
public void run() {
synchronized (p) {
while (p.s <= 'Z') {
if (!p.flag) {
System.out.print(p.s++);
p.flag = true;
p.notifyAll();
} else {
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}