多线程循环交替输出1-100【extends】

来源:互联网 发布:linux进去文件夹 编辑:程序博客网 时间:2024/05/20 07:35
//线程通信。如下的三个关键字使用的话,都得在同步代码块或同步方法中。//wait():一旦一个线程执行到wait(),就释放当前的锁。//notify()/notifyAll():唤醒wait的一个或所有的线程//使用两个线程打印 1-100. 线程1, 线程2 交替打印class PrintNum extends Thread {    static int num = 1;    static Object obj = new Object();    public void run() {        while (true) {            //obj can instead of PrintNum.class            synchronized (obj) {                /*当前线程活动期间才能唤醒其他等待线程*/                obj.notify();                if (num <= 100) {                    try {                        Thread.currentThread().sleep(10);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    System.out.println(Thread.currentThread().getName() + ":"                            + num);                    num++;                } else {                    break;                }                try {                    obj.wait();                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}public class TestCommunication {    public static void main(String[] args) {        Thread t1 = new PrintNum();        Thread t2 = new PrintNum();        t1.setName("thread1");        t2.setName("thread2");        t1.setPriority(Thread.MAX_PRIORITY);//10        t2.setPriority(Thread.MIN_PRIORITY);//1        t1.start();        t2.start();    }}
0 0