线程交替输出

启动三个线程打印递增数字,线程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;
    }
}


 

你可能感兴趣的:(多线程)