经典控制线程执行顺序

使用三个线程控制按照如下格式输出:

线程:1:1
线程:1:2
线程:1:3
线程:1:4
线程:1:5
线程:2:6
线程:2:7
线程:2:8
线程:2:9
线程:2:10
线程:3:11
线程:3:12
线程:3:13
线程:3:14
线程:3:15
线程:1:16
线程:1:17
线程:1:18
线程:1:19
线程:1:20
......
线程:3:71
线程:3:72
线程:3:73
线程:3:74
线程:3:75


逻辑实现类:

public class Service {
    private int num = 0;
    private Integer currentThreadNum = 1;
    public void print() {
        synchronized (this) {
            try {
                while(this.num <= 70) {
                    if(Thread.currentThread().getName().equals(this.currentThreadNum.toString())) {
                        for (int i = 1; i <= 5; i++) {
                            System.out.println("线程:" + currentThreadNum + ":" + (++this.num));
                        }
                        this.currentThreadNum = this.currentThreadNum % 3 + 1;
                        this.notifyAll();
                    }else {
                        this.wait();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


工作线程类:

public class Worker extends Thread{
    private Service service;
    public Worker(String currentThreadNum,Service service){
        this.service = service;
        this.setName(currentThreadNum);
    }
    @Override
    public void run() {
        service.print();
    }
}


程序入口类:

public class Run {
    public static void main(String[] args) {
        Service service = new Service();
        new Worker("1", service).start();
        new Worker("2", service).start();
        new Worker("3", service).start();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36807862/article/details/88899252