方法一:通过共享对象锁加上可见变量来实现。
- public class MyService {
- private volatile int orderNum = 1;
- public synchronized void methodA() {
- try {
- while (orderNum != 1) {
- wait();
- }
- for (int i = 0; i < 2; i++) {
- System.out.println("AAAAA");
- }
- orderNum = 2;
- notifyAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public synchronized void methodB() {
- try {
- while (orderNum != 2) {
- wait();
- }
- for (int i = 0; i < 2; i++) {
- System.out.println("BBBBB");
- }
- orderNum = 3;
- notifyAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public synchronized void methodC() {
- try {
- while (orderNum != 3) {
- wait();
- }
- for (int i = 0; i < 2; i++) {
- System.out.println("CCCCC");
- }
- orderNum = 1;
- notifyAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- import service.MyService;
- public class ThreadAA extends Thread {
- private MyService dbtools;
- public ThreadAA(MyService dbtools) {
- super();
- this.dbtools = dbtools;
- }
- @Override
- public void run() {
- dbtools.methodA();
- }
- }
- import service.MyService;
- public class ThreadBB extends Thread {
- private MyService dbtools;
- public ThreadBB(MyService dbtools) {
- super();
- this.dbtools = dbtools;
- }
- @Override
- public void run() {
- dbtools.methodB();
- }
- }
- import service.MyService;
- public class ThreadCC extends Thread {
- private MyService dbtools;
- public ThreadCC(MyService dbtools) {
- this.dbtools = dbtools;
- }
- @Override
- public void run() {
- dbtools.methodC();
- }
- }
- import extthread.ThreadCC;
- import service.MyService;
- import extthread.ThreadAA;
- import extthread.ThreadBB;
- public class Run {
- public static void main(String[] args) {
- MyService myService = new MyService();
- for (int i = 0; i < 2; i++) {
- ThreadBB output = new ThreadBB(myService);
- output.start();
- ThreadAA input = new ThreadAA(myService);
- input.start();
- ThreadCC threadCC = new ThreadCC(myService);
- threadCC.start();
- }
- }
- }
执行结果: