两线程交替打印数字

问题: 起两个线程,线程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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值