Java - abc 顺线程序执行

  • 时间:
  • 浏览:
  • 来源:互联网

abc 线程顺序执行,是一类问题,可能是1万个循环执行

1 join

这种类似串行,不能能保证最小的临界区执行。

2 多个condition

此方法需要多个condition,100个线程需要100个,1万个需要100个。

3 一个conditon(或者用java的内置锁)

package com.chenyixin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Mythread extends Thread {
  public static final int TOTAL =50000;
    private static volatile AtomicInteger Order = new AtomicInteger(0);
    private final int number;
    private final ReentrantLock lock;
    Condition condition;

    public Mythread(int order, ReentrantLock lock, Condition condition) {
        this.number = order;
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            while (Order.get() != number) {
                try {
                    condition.signal();
                    condition.await();
                } catch (InterruptedException e) {
                }
            }

            System.out.println("run "   + number + " " + System.currentTimeMillis() + " " + Order.get());
            Order.set(Order.addAndGet(1)%TOTAL);
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        List<Mythread> mythreads = new ArrayList<>();

        ReentrantLock lock = new ReentrantLock();
        Condition c = lock.newCondition();
        for (int i = 0; i < TOTAL; i++) {
            mythreads.add(new Mythread(i, lock, c));
        }

        for (Thread t : mythreads) {
            t.start();
        }
    }


}

此方法很简洁,不过当线程数超过50000非常慢,原因在于不断await和sign,while一直做无用功。

4 最简单的方法

本文链接http://www.dzjqx.cn/news/show-617270.html