public class volatile01 {
public static void main(String[] args) {
ThreadDao threadDao = new ThreadDao();
new Thread(threadDao).start();
while (true){
if(threadDao.isFlag()){
System.out.println("------------");
break;
}
}
}
static class ThreadDao implements Runnable{
//插件加了volatile关键字和不加的运行差别
private boolean flag = false;
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
System.out.println("flag = "+flag);
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
}
volatile关键字,当多个线程进行操作共享数据时,可以保证内存中的数据可见
volatile不具备互斥性
volatile不能保证变量的原子性
相较于synchronized是一种较为轻量级的同步策略
public static void main(String[] args) {
AtomicDemo atomicDemo = new AtomicDemo();
for (int i = 0; i < 10; i++) {
new Thread(atomicDemo).start();
}
}
static class AtomicDemo implements Runnable{
private volatile int serialNumber = 0;
public int getSerialNumber() {
return serialNumber++;
}
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+getSerialNumber());
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SKYxE1sz-1669130509612)(https://gitee.com/jerrygrj/img/raw/master/img/image-20210720220109739.png)]
private AtomicInteger serialNumber = new AtomicInteger();
public int getSerialNumber() {
//以原子方式将当前值加 1
return serialNumber.getAndIncrement();
}
static class HelloThread implements Runnable{
//
// private static List list = Collections.synchronizedList(new ArrayList<>());
private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
static {
list.add("AA");
list.add("BB");
list.add("CC");
}
@Override
public void run() {
Iterator<String> it = list.iterator();
while (it.hasNext()){
System.out.println(it.next());
list.add("AA");
}
}
}
CountDownLatchpackage juc04_CountDownLatch闭锁;
import java.util.concurrent.CountDownLatch;
public class TestCountDownLatch {
public static void main(String[] args) {
//闭锁
final CountDownLatch latch = new CountDownLatch(5);
LatchDemo latchDemo = new LatchDemo(latch);
long start = System.currentTimeMillis();
//与上面统一线程数
for (int i = 0; i < 5; i++) {
new Thread(latchDemo).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("耗费时间为"+(end-start));
}
static class LatchDemo implements Runnable{
private CountDownLatch latch;
public LatchDemo(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
synchronized (this){
try {
for (int i = 0; i < 50000; i++) {
if(i%2==0){
System.out.println(i);
}
}
} catch (Exception exception) {
exception.printStackTrace();
}finally {
//递减1
latch.countDown();
}
}
}
}
}
public class TestCallable {
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
//1.执行Callable方式,需要FutureTask实现类的支持,用于接收运算接口
FutureTask<Integer> result = new FutureTask<>(td);
new Thread(result).start();
//2.接收线程运算后的结果
try {
Integer sum = result.get();
System.out.println(sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
static class ThreadDemo implements Callable{
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum+=i;
}
return sum;
}
}
}
创建执行线程的方式三:实现Callable接口
相较于Runnable接口的方式,方法可以有返回值,并且可以抛出异常
上述代码,相当于从主线程分出来一个分支进行计算数值总和,然后通过result.get()方法进行数值和总线程的汇合。
public class TestLock {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket, "1号窗口").start();
new Thread(ticket, "2号窗口").start();
new Thread(ticket, "3号窗口").start();
}
static class Ticket implements Runnable {
private int tick = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock(); //上锁
try {
if (tick > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + " 完成售票,余票为:" + --tick);
}
} finally {
lock.unlock(); //释放锁
}
}
}
}
}
public class TestProductIssue {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor pro = new Productor(clerk);
Consumer cus = new Consumer(clerk);
new Thread(pro,"生产者A").start();
new Thread(cus,"消费者B").start();
new Thread(pro,"生产者C").start();
new Thread(cus,"消费者D").start();
}
static class Clerk{
private int product = 0;
//进货
public synchronized void get(){
while (product>=1){//为了避免虚假唤醒问题,应该总是使用在循环中
System.out.println("产品已满");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ ++product);
this.notifyAll();
}
//卖货
public synchronized void sale(){
while (product <=0){
System.out.println("缺货");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ --product);
this.notifyAll();
}
}
static class Productor implements Runnable{
private Clerk clerk;
public Productor(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.get();
}
}
}
static class Consumer implements Runnable{
private Clerk clerk;
public Consumer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}
}
/**
* 编写一个程序,开启三歌线程,这三个线程的id分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出的结果必须按顺序显示
* 如ABCABCABC...依次递归
*/
public class TestABCAlternate {
public static void main(String[] args) {
AlternateDemo ad = new AlternateDemo();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
ad.loopA(i);
}
}
},"A").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
ad.loopB(i);
}
}
},"B").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
ad.loopC(i);
System.out.println("---------------");
}
}
},"C").start();
}
static class AlternateDemo{
private int number = 1;//表示当前正在执行线程的标记
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
/**
*
* @param totalLoop 循环几轮
*/
public void loopA(int totalLoop){
lock.lock();
try{
//1.判断
if(number!=1){
condition1.await();
}
//2.否则打印
for (int i = 1; i <= 1; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
}
//3. 唤醒
number = 2;
condition2.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void loopB(int totalLoop){
lock.lock();
try{
//1.判断
if(number!=2){
condition2.await();
}
//2.否则打印
for (int i = 1; i <= 1; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
}
//3. 唤醒
number = 3;
condition3.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void loopC(int totalLoop){
lock.lock();
try{
//1.判断
if(number!=3){
condition3.await();
}
//2.否则打印
for (int i = 1; i <= 1; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
}
//3. 唤醒
number = 1;
condition1.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x16eNOno-1669130509617)(https://gitee.com/jerrygrj/img/raw/master/img/image-20210721103927322.png)]
public class TestReadWriteLock {
public static void main(String[] args) {
ReadWriteLockDemo rw = new ReadWriteLockDemo();
new Thread(new Runnable() {
@Override
public void run() {
rw.write((int)Math.random()*101);
}
},"write").start();
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
rw.read();
}
}).start();
}
}
static class ReadWriteLockDemo{
private int num = 0;
private ReadWriteLock lock = new ReentrantReadWriteLock();
public void read(){
lock.readLock().lock();//上锁
try{
System.out.println(Thread.currentThread().getName()+":"+num);
}finally {
lock.readLock().unlock();//释放锁
}
}
public void write(int num){
lock.writeLock().lock();
try{
System.out.println(Thread.currentThread().getName());
this.num = num;
}finally {
lock.writeLock().unlock();
}
}
}
}
/*
* 题目:判断打印的 "one" or "two" ?
*
* 1. 两个普通同步方法,两个线程,标准打印, 打印? //one two
* 2. 新增 Thread.sleep() 给 getOne() ,打印? //one two
* 3. 新增普通方法 getThree() , 打印? //three one two
* 4. 两个普通同步方法,两个 Number 对象,打印? //two one
* 5. 修改 getOne() 为静态同步方法,打印? //two one
* 6. 修改两个方法均为静态同步方法,一个 Number 对象? //one two
* 7. 一个静态同步方法,一个非静态同步方法,两个 Number 对象? //two one
* 8. 两个静态同步方法,两个 Number 对象? //one two
*
* 线程八锁的关键:
* ①非静态方法的锁默认为 this, 静态方法的锁为 对应的 Class 实例
* ②某一个时刻内,只能有一个线程持有锁,无论几个方法。
*/
public class TestThread8Monitor {
public static void main(String[] args) {
Number number = new Number();
Number number2 = new Number();
new Thread(new Runnable() {
@Override
public void run() {
number.getOne();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// number.getTwo();
number2.getTwo();
}
}).start();
/*new Thread(new Runnable() {
@Override
public void run() {
number.getThree();
}
}).start();*/
}
}
class Number{
public static synchronized void getOne(){//Number.class
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.out.println("one");
}
public synchronized void getTwo(){//this
System.out.println("two");
}
public void getThree(){
System.out.println("three");
}
}
java.util.concurrent.Executor : 负责线程的使用与调度的根接口
|--**ExecutorService 子接口: 线程池的主要接口
|--ThreadPoolExecutor 线程池的实现类
|--ScheduledExecutorService 子接口:负责线程的调度
|--ScheduledThreadPoolExecutor :继承 ThreadPoolExecutor, 实现 ScheduledExecutorService,功能强大
public class TestThreadPool {
public static void main(String[] args) {
//1. 创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
ThreadPool tp = new ThreadPool();
//2. 为线程池中的线程分配任务
// pool.submit(tp);
// 提交10此相当于有十个线程
for (int i = 0; i < 10; i++) {
pool.submit(tp);
}
//3. 关闭线程池
pool.shutdown();
}
static class ThreadPool implements Runnable{
private int i =0;
@Override
public void run() {
while (i<=10000){
System.out.println(Thread.currentThread().getName()+":"+i++);
}
}
}
}
public class TestThreadPoolAndCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
List<Future<Integer>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//2. 为线程池中的线程分配任务
Future<Integer> future =
pool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum+=i;
}
return sum;
}
});
list.add(future);
}
for (Future<Integer> f :
list) {
System.out.println(f.get());
}
//3. 关闭线程池
pool.shutdown();
}
}
package juc11_线程池;
import java.util.Random;
import java.util.concurrent.*;
public class TestScheduledThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 5; i++) {
Future<Integer> result = pool.schedule(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(100);//生成随机数
System.out.println(Thread.currentThread().getName() + ":" + num);
return num;
}
}, 1, TimeUnit.SECONDS);
System.out.println(result.get());
}
pool.shutdown();
}
}
public class TestForkJoinPool {
public static void main(String[] args) {
Instant start = Instant.now();
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L, 50000000000L);
Long sum = pool.invoke(task);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//166-1996-10590
}
@Test
public void test1(){
Instant start = Instant.now();
long sum = 0L;
for (long i = 0L; i <= 50000000000L; i++) {
sum += i;
}
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//35-3142-15704
}
//java8 新特性
@Test
public void test2(){
Instant start = Instant.now();
Long sum = LongStream.rangeClosed(0L, 50000000000L)
.parallel()
.reduce(0L, Long::sum);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//1536-8118
}
}
class ForkJoinSumCalculate extends RecursiveTask<Long>{
/**
*
*/
private static final long serialVersionUID = -259195479995561737L;
private long start;
private long end;
private static final long THURSHOLD = 10000L; //临界值
public ForkJoinSumCalculate(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long length = end - start;
if(length <= THURSHOLD){
long sum = 0L;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
}else{
long middle = (start + end) / 2;
ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
left.fork(); //进行拆分,同时压入线程队列
ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle+1, end);
right.fork(); //
return left.join() + right.join();
}
}
}