JDK21虚拟线程完成经典的并发实验

2023-12-22  本文已影响0人  JohnYuCN

1. 启动虚拟线程的方法:

# 方法一: 
Thread.ofVirtual().name("线程名称").start([Runnable接口对象]);
# 方法二:
ExecutorService service = Executors.newVirtualThreadPerTaskExecutor();
service.submit([Runnable接口对象])

2. 线程同步: 多点售票

package cn.johnyu;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test1 {
    //填充一个售票池,有100张票
    private static Vector<Integer> pool = new Vector<>();
//    private static List<Integer> pool = new ArrayList<>();
    static {
        for (int i = 1; i < 101; i++) {
            pool.add(i);
        }
    }

    public static void main(String[] args) throws Exception {
//        新建虚拟线程池(此方法的缺点是无法给每个虚拟线程分配名称)
//        ExecutorService service = Executors.newVirtualThreadPerTaskExecutor();
//        for (int i = 0; i < 8; i++) {
//            service.submit(Test1::sale1);
//        }
        //启动多个虚拟线程,进行多点售票
        for (int i = 0; i < 8; i++) {
            Thread.ofVirtual().name("线程" + i).start(Test1::sale1);
        }
        
        System.in.read();//必需滴: 主线程结束,会终止所有的非daemon线程,而虚拟线程所依托的OS Thread都是non-daemon
    }

    private static void sale1() {
        while (!pool.isEmpty()) {
            //1.当使用一个线程安全的集合对象做为锁时,当集合为空时,排队等待的线程会自动销毁
            //2.当使用一个非线程案例的集合对象做为锁时,当集合为空时,排队线程仍然会进入同步代码块中,从而导致集合越界异常
            //  可以考虑在代码块内部加入if(!pool.isEmpty())进行处理
            synchronized (pool) {
                Integer t = pool.get(0);
                System.out.println(Thread.currentThread().getName() + " 查询到票号: " + t);
                //如不进行同步控制,会导致多个线程删除同一张票
                // (如果使用ArrayList,可能会有多于一个线程返回true,导致一票多售)
                // (如果使用Vector,只会有一个线程返回true,不会一票多售,但会出票失败)
                sleep(10);
                boolean remove = pool.remove(t);
                if (remove) System.out.println(Thread.currentThread().getName() + " 已经售票.............: " + t);
                else System.out.println(Thread.currentThread().getName() + " 出票失败");
            }
            Thread.yield(); //或者sleep(1),目的是:当前线程脱离同步代码块后,可以让其它线程有机会进入
        }
    }

    public static void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}


3. 线程通信: 生产者、消费者

package cn.johnyu;

import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.SynchronousQueue;

public class Test3 {
    public static void main(String[] args) throws Exception{
        Queue<Double> queue=new LinkedList<>();
        Thread.ofVirtual().name("consumer").start(new Consumer(queue));
        Thread.ofVirtual().name("producer").start(new Producer(queue));
        System.in.read();
    }
}
class Consumer implements Runnable{
    private Queue<Double> queue;

    public Consumer(Queue<Double> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true){
            synchronized (queue){
                try {
                    if(queue.size()<2){
                        double random = Math.random();
                        queue.add(random);
                        System.out.printf("( %s )生产者生产了: %f\n",Thread.currentThread().getName(),random);
                        queue.notify();
                        Thread.sleep(100);
                    }else {
                        queue.wait();
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

class Producer implements Runnable{
    private Queue<Double> queue;

    public Producer(Queue<Double> queue) {
        this.queue = queue;
    }
    @Override
    public void run() {
        while (true){
            synchronized (queue) {
                try {
                    if(queue.size()>0){

                        double poll = queue.poll();
                        System.out.printf("( %s )消费者消费了.............: %f\n",Thread.currentThread().getName(),poll);
                        queue.notify();
                        Thread.sleep(1000);
                    }
                    else{
                        queue.wait();
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读