JDK21虛擬線程完成經(jīng)典的并發(fā)實(shí)驗(yàn)

1. 啟動(dòng)虛擬線程的方法:

# 方法一: 
Thread.ofVirtual().name("線程名稱").start([Runnable接口對(duì)象]);
# 方法二:
ExecutorService service = Executors.newVirtualThreadPerTaskExecutor();
service.submit([Runnable接口對(duì)象])

2. 線程同步: 多點(diǎn)售票

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 {
    //填充一個(gè)售票池,有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 {
//        新建虛擬線程池(此方法的缺點(diǎn)是無法給每個(gè)虛擬線程分配名稱)
//        ExecutorService service = Executors.newVirtualThreadPerTaskExecutor();
//        for (int i = 0; i < 8; i++) {
//            service.submit(Test1::sale1);
//        }
        //啟動(dòng)多個(gè)虛擬線程,進(jìn)行多點(diǎn)售票
        for (int i = 0; i < 8; i++) {
            Thread.ofVirtual().name("線程" + i).start(Test1::sale1);
        }
        
        System.in.read();//必需滴: 主線程結(jié)束,會(huì)終止所有的非daemon線程,而虛擬線程所依托的OS Thread都是non-daemon
    }

    private static void sale1() {
        while (!pool.isEmpty()) {
            //1.當(dāng)使用一個(gè)線程安全的集合對(duì)象做為鎖時(shí),當(dāng)集合為空時(shí),排隊(duì)等待的線程會(huì)自動(dòng)銷毀
            //2.當(dāng)使用一個(gè)非線程案例的集合對(duì)象做為鎖時(shí),當(dāng)集合為空時(shí),排隊(duì)線程仍然會(huì)進(jìn)入同步代碼塊中,從而導(dǎo)致集合越界異常
            //  可以考慮在代碼塊內(nèi)部加入if(!pool.isEmpty())進(jìn)行處理
            synchronized (pool) {
                Integer t = pool.get(0);
                System.out.println(Thread.currentThread().getName() + " 查詢到票號(hào): " + t);
                //如不進(jìn)行同步控制,會(huì)導(dǎo)致多個(gè)線程刪除同一張票
                // (如果使用ArrayList,可能會(huì)有多于一個(gè)線程返回true,導(dǎo)致一票多售)
                // (如果使用Vector,只會(huì)有一個(gè)線程返回true,不會(huì)一票多售,但會(huì)出票失敗)
                sleep(10);
                boolean remove = pool.remove(t);
                if (remove) System.out.println(Thread.currentThread().getName() + " 已經(jīng)售票.............: " + t);
                else System.out.println(Thread.currentThread().getName() + " 出票失敗");
            }
            Thread.yield(); //或者sleep(1),目的是:當(dāng)前線程脫離同步代碼塊后,可以讓其它線程有機(jī)會(huì)進(jìn)入
        }
    }

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


3. 線程通信: 生產(chǎn)者、消費(fèi)者

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 )生產(chǎn)者生產(chǎn)了: %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èi)者消費(fèi)了.............: %f\n",Thread.currentThread().getName(),poll);
                        queue.notify();
                        Thread.sleep(1000);
                    }
                    else{
                        queue.wait();
                    }

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容