一道面试题:通过wait和notify的两个线程交互输出thread1-1...thread1-5,thread2-6...thread2-10...

来源:互联网 发布:apache 支持cgi 配置 编辑:程序博客网 时间:2024/05/22 08:08

这是一道关于多线程的面试题,好久没有做过这种多线程的题了,手有点生,那么就来敲一敲

package threadDemo;/* * 多线程的交叉打印 */public class threaddemo1 {    public static void main(String[] args) {        num num = new num();        Thread t1 = new Thread(new thread1(num));        Thread t2 = new Thread(new thread1(num));        t1.start();        t2.start();    }}class num {    public int count;    public num() {    }}class thread1 implements Runnable {    private final num num;    public thread1(num num) {        this.num = num;    }    @Override    public void run() {            synchronized (num) {            while (num.count <= 20) {                for (int i = 0; i < 5; i++) {                    System.out.println(Thread.currentThread().getName() + "-"                            + num.count++);                }                num.notify();                try {                    num.wait();                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}
阅读全文
1 0