用Java多线程实现循环打印数字
方式一:使用java的synchronized锁实现
public class LoopPrint implements Runnable {
public static volatile AtomicInteger totalThread = new AtomicInteger(0);
public static volatile AtomicInteger point = new AtomicInteger(1);
private static final Object lockObj = new Object();
private int id;
public LoopPrint(int id,int total) {
totalThread.set(total);
this.id = id;
}
@Override
public void run() {
while (true){
synchronized (lockObj){
int i = point.get();
if (i==id){
System.out.println("线程"+this.id+":当前值为:"+i);
lockObj.notify();
if (i == totalThread.get()){
point.set(1);
}else{
point.addAndGet(1);
}
try {
lockObj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new Thread( new LoopPrint(1,9)).start();
new Thread( new LoopPrint(2,9)).start();
new Thread( new LoopPrint(3,9)).start();
new Thread( new LoopPrint(4,9)).start();
new Thread( new LoopPrint(5,9)).start();
new Thread( new LoopPrint(6,9)).start();
new Thread( new LoopPrint(7,9)).start();
new Thread( new LoopPrint(8,9)).start();
new Thread( new LoopPrint(9,9)).start();
}
}
方式二:使用JUC包中的lock及Condition实现
public class LoopPrint3 implements Runnable{
private static ReentrantLock lock = new ReentrantLock();
private static AtomicInteger total = new AtomicInteger(0);
private static List<Condition> conditions = new ArrayList<>();
private static volatile int point = 0;
private int id;
public LoopPrint3() {
conditions.add(lock.newCondition());
this.id = total.getAndAdd(1);
}
@Override
public void run() {
try {
lock.lock();
while (true){
if (point != id){
conditions.get(id).await();
}
System.out.println(Thread.currentThread().getName()+":"+(++point));
if (point ==total.get() ){
point = 0;
}
if (id == total.get()-1){
conditions.get(0).signal();
}else{
conditions.get(id+1).signal();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
new Thread(new LoopPrint3()).start();
new Thread(new LoopPrint3()).start();
new Thread(new LoopPrint3()).start();
new Thread(new LoopPrint3()).start();
new Thread(new LoopPrint3()).start();
}
}