我们要让两个线程交替执行,可以通过Object对象的wait()
方法 和 notify()
方法实现。
先上代码:
public class Test {
public static void main(String[] args) {
final Printer printer = new Printer();
//启动线程1
new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
printer.print1();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
//启动线程2
new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
printer.print2();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class Printer {
private int flag = 1;
public void print1() throws Exception {
synchronized(this) {
if (flag != 1) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + " : 11111");
flag = 2;
this.notify();
}
}
public void print2() throws Exception {
synchronized(this) {
if (flag != 2) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + " : 22222");
flag = 1;
this.notify();
}
}
}
这段代码会交替的输出 11111
和 22222
。
- 在同步代码块中锁对象是谁,就用谁来调用
wait()
或notify()
方法。 sleep()
方法和wait()
方法的区别
sleep()
方法必须传入参数(毫秒),然后睡眠指定的时间之长,同时不释放同步锁,会自动醒来。wait()
方法可选传入参数(毫秒),如果没有参数则开始等待,如果有则等到参数的时间再开始等待,且会释放同步锁,不会自动醒来。