Java线程间通信:wait和notify以及交替执行

看了网上很多讲线程间通信的文章,很多以交替执行给出例子;但是有些明显是有问题的,于是我自己也写了个例子。

线程间通信:wait 和notify

  • wait()方法是指当前线程对对象的控制等待。对对象的控制权移交给其他线程
  • notify()方法是指通知某个正在等待当前线程控制权的线程,可以继续进行

代码示例

两个线程,线程A:1、3、5、7…97、99 ,线程B打印:2、4、6、8、10…、98、100,交替打印

WorkerPrinter 的例子

static private class PrinterWorker implements Runnable {

        private Object sharedObject;
        private int breakPoint = 100;
        private int number = 1;

        public PrinterWorker(Object sharedObject, int breakPoint) {
            this.sharedObject = sharedObject;
            this.breakPoint = breakPoint;
        }

        @Override
        public void run() {
            for (; number <= 100; ) {
                synchronized (sharedObject) {
                    sharedObject.notify();

                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;

                    if (number <= breakPoint) {
                        try {
                            sharedObject.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }

运行:

public static void run(String[] args) {
        Object sharedObject = new Object();
        PrinterWorker printer = new PrinterWorker(sharedObject, 100);

        Thread worker1 = new Thread(printer, "thread-A");
        Thread worker2 = new Thread(printer, "thread-B");
        worker1.start();
        worker2.start();
    }

测试结果:

thread-A:1
thread-B:2
thread-A:3
thread-B:4
thread-A:5
.
.
.
thread-B:96
thread-A:97
thread-B:98
thread-A:99
thread-B:100

(完)

发表评论

邮箱地址不会被公开。 必填项已用*标注