java多线程通信问题

wait(100L)意思为:不占用CPU,线程等待100毫秒

notify():唤醒正在排队等待同步资源的线程优先级最高者结束等待。

notifyAll():唤醒所有正在排队等待同步资源的线程。

并且这三个方法必须在synchronized块内执行否则会报异常

让两个线程循环打印1-100比如a打印1,b打印1,a2,b2

package com.thread.test1;

public class TestPrintOne {

    /**
     * @param args
     */
    public static void main(String[] args) {
        PrintOne one = new PrintOne();
        Thread t1 = new Thread(one);
        Thread t2 = new Thread(one);

        t1.setName("1");
        t2.setName("2");

        t1.start();
        t2.start();

    }

}

class PrintOne implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            synchronized (this) {
                //进入同步块的时候进行唤醒
                notifyAll();
                System.out
                        .println(Thread.currentThread().getName() + "打印的" + i);

                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}
原文地址:https://www.cnblogs.com/84126858jmz/p/5693962.html