如何用java的虚拟线程连接数据库

我觉得这个很简单

首先确保你idea支持jdk21.

然后把idea编译成的目标字节码设置为21版本的

然后编写代码。

创建虚拟线程的方式有:

Runnable runnable = () -> {
    System.out.println("Hello, world!");
};

// 创建虚拟线程
Thread virtualThread = Thread.startVirtualThread(runnable);

// 开始虚拟线程
Thread.ofVirtual()
        .name("my-virtual001")
        .start(runnable);
Runnable runnable = () -> {
    System.out.println("Hello!");
};

try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 100; i++) {
        executorService.submit(runnable);
    }
}
Runnable runnable = () -> {
    System.out.println("Hello!");
};

ThreadFactory virtualThreadFactory = Thread.ofVirtual()
        .name("qian", 0)
        .factory();

Thread factoryThread = virtualThreadFactory.newThread(runnable);
factoryThread.start();

然后编写连接数据库的代码:(记住引入java连接mysql的驱动)

package org.tianfan.mysqlTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.concurrent.ThreadFactory;

public class Test001 {
    static String name = "root";
    static String password = "123456";
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/itheima?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    public static void main(String[] args) throws InterruptedException {

        Runnable runnable = () -> {
            Connection conn = null;
            Statement stmt = null;
            try {
                // 注册 JDBC 驱动
                Class.forName(JDBC_DRIVER);

                // 打开链接
                System.out.println("连接数据库...");
                conn = DriverManager.getConnection(DB_URL, name, password);
                System.out.println("连接成功...");

            }catch (Exception e){
                e.printStackTrace();
            }
        };


// 使用静态构建器方法
        Thread virtualThread = Thread.startVirtualThread(runnable);

        Thread.sleep(1000);
    }

}

结果展示图:

posted @ 2023-11-23 00:24  过移  阅读(78)  评论(0编辑  收藏  举报  来源