创建打印Service
方法一
锁方法
public class Service {
public synchronized void print(int num){
try {
this.notify();
System.out.println(Thread.currentThread().getName()+ ": " + num);
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
方法二
锁this对象
public class Service {
public void print(int num){
try {
synchronized (this) {
this.notify();
System.out.println(Thread.currentThread().getName() + ": " + num);
this.wait();
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
方法三
可重入锁+队列
public class Service {
private ReentrantLock reentrantLock = new ReentrantLock();
private Condition condition = reentrantLock.newCondition();
public void print(int num){
try {
reentrantLock.lock();
condition.signal();//唤醒一个等待在condition上的线程,将该线程从等待队列中转移到同步队列中,如果在同步队列中能够竞争到Lock则可以从等待方法
System.out.println(Thread.currentThread().getName() + ": " + num);
condition.await();//得当前获取lock的线程进入到等待队列, 如果该线程能够从await()方法返回的话一定是该线程获取了与condition相关联的lock
}catch (InterruptedException e){
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
}
线程A
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service) {
this.service = service;
}
@Override
public void run() {
for (int i = 1; i <= 10; i += 2) {
service.print(i);
}
}
}
线程B
public class ThreadB extends Thread {
private Service service;
public ThreadB(Service service) {
this.service = service;
}
@Override
public void run() {
for (int i = 2; i <= 10; i += 2) {
service.print(i);
}
}
}
测试
public class TestMain {
public static void main(String[] args) {
Service service = new Service();
ThreadA threadA = new ThreadA(service);
ThreadB threadB = new ThreadB(service);
threadA.setName("A");
threadB.setName("B");
threadA.start();
threadB.start();
}
}