按照这个格式输出你会吗???
你说你不会,接下来认真看认真学了。
1.首先引入原子类。AtomicInteger num = new AtomicInteger(0);
什么是原子类?
就是可以保证线程安全的原子操作的数据类型。
有什么作用?
原子类的作用和锁类似,为了保证并发情况下的线程安全。原子类和锁相比,要比锁的粒度更细,效率更高
2.引入公平锁。ReentrantLock lock = new ReentrantLock(true);
什么是公平锁?
是指多个线程按照申请锁的顺序来获取锁,类似于排队买饭,先来后到,先来先服务,就是公平的,也就是队列
3.看代码,这里开启三个线程
Ex7 e=new Ex7();var a=new Thread(e::work,"A");a.start();var b=new Thread(e::work,"B");b.start();var c=new Thread(e::work,"C");c.start();
4.写一个死循环,进入循环就开启锁,结束一次循环就开锁,因为是公平锁所以,我们是根据线程一个一个进行执行。
String tn = Thread.currentThread().getName();while (true) {lock.lock();try {TimeUnit.SECONDS.sleep(1);} catch (Exception e) {e.printStackTrace();}System.out.printf("%s%d ",tn,num.incrementAndGet());if ("C".equals(tn)){System.out.println();}lock.unlock();}
5.整体代码。
/** Copyright (c) 2020, 2023, All rights reserved.**/
package cn;import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;/*** <p>Project: JavaStudy - Ex7</p>* <p>Powered by scl On 2023-07-27 21:15:09</p>* <p>描述:<p>** @author scl [1846080280@qq.com]* @version 1.0* @since 17*/
public class Ex7 {AtomicInteger num = new AtomicInteger(0);//手动锁 加一个true变成公平锁ReentrantLock lock = new ReentrantLock(true);public static void main(String[] args) {Ex7 e=new Ex7();var a=new Thread(e::work,"A");a.start();var b=new Thread(e::work,"B");b.start();var c=new Thread(e::work,"C");c.start();}void work() {String tn = Thread.currentThread().getName();while (true) {lock.lock();try {TimeUnit.SECONDS.sleep(1);} catch (Exception e) {e.printStackTrace();}System.out.printf("%s%d ",tn,num.incrementAndGet());if ("C".equals(tn)){System.out.println();}lock.unlock();}}
}
6.看效果。。。。