两线程交替打印数字

来源:互联网 发布:软件下载源码 编辑:程序博客网 时间:2024/06/05 12:05

问题: 起两个线程,线程1打印奇数,线程2打印偶数,两线程交替打印。
解决方法: 通过wait(),notify()实现。
注:之前是用的wait(),后来运行时,发现最后总有一个线程牌阻塞状态,因此采用的wait(1000)。
代码如下:

package thread;public class ThreadTest {    private static Object LOCK = new Object();    private static int i=1;    public static void main(String[] args) {        Thread thread1 = new Thread() {                public void run() {                    while(i<=10) {                        synchronized (LOCK) {                            if(i%2==0){                                System.out.println("Thread1: "+i++);                            }else{                                LOCK.notifyAll();                                 try {                                        LOCK.wait(1000);                                      } catch (InterruptedException e) {                                               e.printStackTrace();                                      }                                }                            }                    }                }        };        Thread thread2 = new Thread() {            public void run() {                while(i<=10) {                    synchronized (LOCK) {                        if(i%2!=0){                            System.out.println("Thread2: "+i++);                        }else{                            LOCK.notifyAll();                             try {                                    LOCK.wait(1000);                                  } catch (InterruptedException e) {                                           e.printStackTrace();                                  }                            }                        }                }            }        };        thread1.start();        thread2.start();}}

运行结果:
Thread-1 1
Thread-0 2
Thread-1 3
Thread-0 4
Thread-1 5
Thread-0 6
Thread-1 7
Thread-0 8
Thread-1 9
Thread-0 10

0 0
原创粉丝点击