1、线程1负责输出abcd
public class Thread1 extends Thread {
//定义锁对象,负责接收传入对象
private final Object lock;
//定义共有构造方法
public Thread1(Object lock) {
// TODO Auto-generated constructor stub
this.lock = lock;
}
@Override
public void run() {
String[] string = {"a", "b", "c", "d"};
for (int i = 0; i < string.length; i++) {
synchronized (lock) {
//线程1开始执行
lock.notify();
try {
//线程1开始等待
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//线程1继续执行
System.out.print(string[i]);
//线程1运行结束
lock.notify();
}
}
}
}
2、线程2负责输出1234
public class Thread2 extends Thread {
//定义锁对象,负责接收传入对象
private final Object lock;
//定义共有构造方法
public Thread1(Object lock) {
// TODO Auto-generated constructor stub
this.lock = lock;
}
@Override
public void run() {
String[] string = {"1", "2", "3", "4"};
for (int i = 0; i < string.length; i++) {
synchronized (lock) {
//线程2开始执行
lock.notify();
try {
//线程2开始等待
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//线程2继续执行
System.out.print(string[i]);
//线程2运行结束
lock.notify();
}
}
}
}
3、创建测试类
public class Test {
public static void main(String[] args){
// TODO Auto-generated method stub
final Object lock = new Object();
Thread1 t1 = new Thread1(lock);
Thread2 t2 = new Thread2(lock);
t1.start();
t2.start();
}
}
输出结果
a1b2c3d4