线程交替输出

启动三个线程打印递增数字,线程1先打印1,2,3,4,5 然后是线程2打印6,7,8,9,10然后是线程3打印出11,12,13,14,15.接着在由线程1打印16,17,18,19,20.以此类推打印到75.代码如下:
package com.test;
public class MyFirstThread {
    private static CommonObj lock;
    public static void main (String[] args){
        lock =new CommonObj(0,1);
        Thread thread1 = new Thread(new  FirstRunnable(lock,1,2),"线程1");
        Thread thread2 = new Thread(new  FirstRunnable(lock,2,3),"线程2");
        Thread thread3 = new Thread(new  FirstRunnable(lock,3,1),"线程3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

package com.test;
public class CommonObj {
    private  int n;
    private  int status;
    public CommonObj(int n ,int status){
        this.n = n;
        this.status = status;
    }
    public  int getN() {
        return n;
    }
    public  void setN(int n) {
        this.n = n;
    }
    public  int getStatus() {
        return status;
    }
    public  void setStatus(int status) {
        this.status = status;
    }
    public int addN(int no){
        return n=n+no;
    }
}


package com.test;
public class FirstRunnable implements Runnable {

    private  CommonObj lock ;
    private int currentStatuc;
    private int nextStatus;

    public  FirstRunnable (CommonObj lock,int currentStatuc,int nextStatus){
        this.lock = lock;
        this.currentStatuc = currentStatuc;
        this.nextStatus = nextStatus;
    }
    @Override
    public void run() {
        for(int j=0;j<5;j++){
            synchronized (lock){
                while(lock.getStatus()!=currentStatuc){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.setStatus(nextStatus);
                for(int i=0;i<5;i++){
                    System.out.println(Thread.currentThread().getName()+"now Number : "+lock.addN(1)+" currentStatuc "+currentStatuc+" nextStatus "+nextStatus);
                }
                lock.notifyAll();
                System.out.println(" lock.getStatus "+lock.getStatus());
            }
        }
    }

    public CommonObj getLock() {
        return lock;
    }

    public void setLock(CommonObj lock) {
        this.lock = lock;
    }

    public int getNextStatus() {
        return nextStatus;
    }

    public void setNextStatus(int nextStatus) {
        this.nextStatus = nextStatus;
    }
}


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值