Class -- 05 -- TimeUnit类常用方法解析

本文详细介绍了Java中的TimeUnit类,包括其定义、枚举常量及常用方法,并通过实例展示了如何进行时间单位间的转换和线程的延时操作。

原文链接:Class – 05 – TimeUnit类常用方法解析


相关文章:


这次主要整理下 Java 中 TimeUnit 类的常用方法


一、TimeUnit类的定义

  • TimeUnit 类位于 java.util.concurrent 包中,是一个枚举类,主要用于时间颗粒度的转换与线程的延时

  • TimeUnit 包含以下七个枚举常量

    常量名含义
    NANOSECONDS纳秒,等于 $1 * 10^{-9}s$
    MICROSECONDS微秒,等于 $1 * 10^{-6}s$
    MILLISECONDS毫秒,等于 $1 * 10^{-3}s$
    SECONDS
    MINUTES
    HOURS
    DAYS

二、TimeUnit 类常用方法

  • toDays(long duration)

    • 将指定颗粒度的时间转换为天数

      // 将1天转换为天数
      System.out.println(TimeUnit.DAYS.toDays(1)); // 1
      

  • toHours(long duration)

    • 将指定颗粒度的时间转换为小时数

      // 将1天转换为小时数
      System.out.println(TimeUnit.DAYS.toHours(1)); // 24
      

  • toMinutes(long duration)

    • 将指定颗粒度的时间转换为分数

      // 将1天转换为分数
      System.out.println(TimeUnit.DAYS.toMinutes(1)); // 1440
      

  • toSeconds(long duration)

    • 将指定颗粒度的时间转换为秒数

      // 将1天转换为秒数
      System.out.println(TimeUnit.DAYS.toSeconds(1)); // 86400
      

  • toMillis(long duration)

    • 将指定颗粒度的时间转换为毫秒数

      // 将1天转换为毫秒数
      System.out.println(TimeUnit.DAYS.toMillis(1)); // 86400000
      

  • toMicros(long duration)

    • 将指定颗粒度的时间转换为微秒数

      // 将1天转换为微秒数
      System.out.println(TimeUnit.DAYS.toMicros(1)); // 86400000000
      

  • toNanos(long duration)

    • 将指定颗粒度的时间转换为纳秒数

      // 将1天转换为纳秒数
      System.out.println(TimeUnit.DAYS.toNanos(1)); // 86400000000000
      

  • convert(long sourceDuration, TimeUnit sourceUnit)

    • 将参数颗粒度时间转换为指定颗粒度时间

      // 将48小时转换为天数
      System.out.println(TimeUnit.DAYS.convert(48, TimeUnit.HOURS)); // 2
      

  • compareTo(E o)

    • 比较两个枚举常量的索引值大小,返回一个差值

      image

      // [NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS]
      System.out.println(Arrays.toString(TimeUnit.values())); 
      // DAYS的索引值为6
      System.out.println(TimeUnit.DAYS.ordinal()); //6
      // MINUTES的索引值为4
      System.out.println(TimeUnit.MINUTES.ordinal()); // 4
      System.out.println(TimeUnit.DAYS.compareTo(TimeUnit.MINUTES)); // 2
      System.out.println(TimeUnit.MINUTES.compareTo(TimeUnit.DAYS)); // -2
      

  • sleep(long timeout)

    • 提供了可读性更好的线程休眠操作,使线程休眠指定时间颗粒度的时间,通常用来替换 Thread.sleep()

    • 当使用 Thread.sleep() 方法时,由于输入的参数为毫秒数,所以很难直观地看出当前线程具体休眠了多长时间

      Thread.sleep(2000);
      // 休眠2秒钟 (时间颗粒度为秒)
      TimeUnit.SECONDS.sleep(2);
      // 休眠2分钟 (时间颗粒度为分)
      TimeUnit.MINUTES.sleep(2)
      

  • timedJoin(Thread thread, long timeout)

    • 对指定线程,休眠指定时间颗粒度的时间

      // 对当前线程休眠2秒
      TimeUnit.SECONDS.timedJoin(Thread.currentThread(), 2);
      

  • timedWait(Object obj, long timeout)

    • 对指定对象,休眠指定时间颗粒度的时间

      public class Test {
      	// 此处需要使用synchronized关键字将方法锁住
          public synchronized void show() throws InterruptedException {
              TimeUnit.SECONDS.timedWait(this, 2);
              System.out.println("HelloWorld");
          }
          
      	public static void main(String[] args) throws InterruptedException {
              Test test = new Test();
              // 2秒之后执行
              test.show();
          }
      }
      
<think> 我们正在讨论Java调用DeepSeek API(DeepSeek-V3-0324)的方法。根据提供的引用,特别是引用[2]中的代码片段,我们可以看到一个使用Spring Boot框架的示例。这个示例展示了一个简单的控制器,它通过HTTP POST请求接收一个提示(prompt),然后调用DeepSeekService来与DeepSeek API交互,并返回API的响应内容。 注意:引用[1]中提到了DeepSeek API是基于RESTful架构的,并且需要API密钥。因此,在实现时,我们需要获取API密钥,并在请求中包含它。 以下是实现Java调用DeepSeek API(DeepSeek-V3-0324)的步骤: 1. **获取API密钥**:首先,你需要在DeepSeek平台注册账号并获取API密钥(通常可以在用户设置或API管理页面找到)。 2. **创建HTTP客户端**:我们需要一个HTTP客户端来发送POST请求到DeepSeek API的端点。可以使用Java的HttpURLConnection,或者更常用的库如Apache HttpClient、OkHttp或Spring的RestTemplate。 3. **构建请求**:DeepSeek API的请求应该是JSON格式,包含必要的参数,例如模型名称(model,这里使用"deepseek-chat"或指定版本如"deepseek-chat-v3-0324")、消息列表(messages)等。根据引用[2],请求体至少包含一个提示(prompt),但实际上,DeepSeek API可能需要按照其文档要求构建消息数组。 4. **设置认证**:在HTTP请求头中添加认证信息,通常是Bearer Token,即你的API密钥。 5. **发送请求并处理响应**:发送请求后,解析返回的JSON响应,提取需要的内容。 由于引用[2]中使用了Spring Boot,我们可以继续使用似的框架。下面我将提供一个更完整的示例,包括Service层的实现。 ### 步骤详解 #### 步骤1:添加依赖(如果使用Spring Boot和RestTemplate) 在`pom.xml`中添加以下依赖(以Maven为例): ```xml <dependencies> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- JSON处理 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies> ``` #### 步骤2:配置API密钥 在`application.properties`或`application.yml`中配置你的API密钥: ```properties deepseek.api.key=your_api_key_here deepseek.api.url=https://api.deepseek.com/v1/chat/completions # 根据实际API地址调整 ``` #### 步骤3:创建请求和响应的Java 根据DeepSeek API的文档,我们需要定义请求体和响应体的结构。以下是一个简化的示例: **请求体**: ```java public class DeepSeekRequest { private String model; // 模型名称,如"deepseek-chat" private List<Message> messages; // 构造方法、getter和setter public static class Message { private String role; private String content; // 构造方法、getter和setter } } ``` **响应体**: ```java public class DeepSeekResponse { private List<Choice> choices; // getter和setter public static class Choice { private Message message; // getter和setter public static class Message { private String content; // getter和setter } } } ``` #### 步骤4:实现Service层 使用RestTemplate发送请求: ```java @Service public class DeepSeekService { @Value("${deepseek.api.url}") private String apiUrl; @Value("${deepseek.api.key}") private String apiKey; public DeepSeekResponse callChatApi(String prompt) { // 创建请求体 DeepSeekRequest request = new DeepSeekRequest(); request.setModel("deepseek-chat-v3-0324"); // 指定模型版本 List<DeepSeekRequest.Message> messages = new ArrayList<>(); messages.add(new DeepSeekRequest.Message("user", prompt)); request.setMessages(messages); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(apiKey); // 使用Bearer Token认证 HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers); // 发送请求 RestTemplate restTemplate = new RestTemplate(); ResponseEntity<DeepSeekResponse> response = restTemplate.exchange( apiUrl, HttpMethod.POST, entity, DeepSeekResponse.class ); return response.getBody(); } } ``` #### 步骤5:创建Controller 如引用[2]中的控制器: ```java @RestController @RequestMapping("/deepseek") public class DeepSeekController { @Autowired private DeepSeekService deepSeekService; @PostMapping("/chat") public String getResponse(@RequestBody String prompt) { DeepSeekResponse response = deepSeekService.callChatApi(prompt); // 假设响应中至少有一个选择 if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) { return response.getChoices().get(0).getMessage().getContent(); } return "No response"; } } ``` ### 测试 你可以使用Postman或curl发送POST请求到`http://localhost:8080/deepseek/chat`,请求体为字符串(即提示内容),例如: ```json "请介绍一下你自己" ``` ### 注意事项 - 错误处理:在实际应用中,需要添加适当的错误处理(例如,网络错误、API返回错误等)。 - 模型版本:根据你的需求,模型名称可能需要调整(如使用`deepseek-chat`或指定的版本号)。 - API文档:建议参考DeepSeek官方API文档,以获取最新的端点和参数要求。 ### 引用说明 以上实现参考了引用[2]中的基本结构,并扩展了细节[^2]。 §§相关问题§§ 1. 如何获取DeepSeek的API密钥? 2. 除了Spring Boot,还有其他方式在Java中调用DeepSeek API吗? 3. 如何处理DeepSeek API调用中的异常情况? </think> 以下是Java调用DeepSeek API(DeepSeek-V3-0324)的完整实现方案,基于官方API文档和最佳实践整理: ### 一、调用前准备 1. **获取API密钥** 登录DeepSeek平台 → 开发者中心 → 创建API密钥(需实名认证)[^1] ```java final String API_KEY = "sk-your_api_key_here"; // 替换为实际密钥 ``` 2. **添加依赖** 在`pom.xml`中添加HTTP客户端和JSON库: ```xml <dependencies> <!-- OkHttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.12.0</version> </dependency> <!-- Gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> </dependencies> ``` --- ### 二、Java调用实现 #### 1. 请求模型 ```java public class DeepSeekRequest { private String model = "deepseek-chat-v3-0324"; private List<Message> messages; // 静态内部 public static class Message { private String role; private String content; // 构造方法/getters/setters } } ``` #### 2. 核心调用方法 ```java import okhttp3.*; import com.google.gson.Gson; public class DeepSeekClient { private static final String API_URL = "https://api.deepseek.com/v1/chat/completions"; public static String callDeepSeekAPI(String userPrompt) throws IOException { // 组装请求体 DeepSeekRequest.Message message = new DeepSeekRequest.Message(); message.setRole("user"); message.setContent(userPrompt); DeepSeekRequest request = new DeepSeekRequest(); request.setMessages(Collections.singletonList(message)); // 创建HTTP请求 OkHttpClient client = new OkHttpClient(); Gson gson = new Gson(); RequestBody body = RequestBody.create( gson.toJson(request), MediaType.parse("application/json") ); Request httpRequest = new Request.Builder() .url(API_URL) .post(body) .addHeader("Authorization", "Bearer " + API_KEY) .addHeader("Content-Type", "application/json") .build(); // 执行请求并解析响应 try (Response response = client.newCall(httpRequest).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code: " + response); } JsonObject jsonResponse = gson.fromJson( response.body().string(), JsonObject.class ); return jsonResponse.getAsJsonArray("choices") .get(0).getAsJsonObject() .getAsJsonObject("message") .get("content").getAsString(); } } } ``` #### 3. Spring Boot控制器示例 ```java @RestController @RequestMapping("/api/deepseek") public class DeepSeekController { @PostMapping("/chat") public String chat(@RequestBody String prompt) { try { return DeepSeekClient.callDeepSeekAPI(prompt); } catch (IOException e) { return "{\"error\":\"" + e.getMessage() + "\"}"; } } } ``` --- ### 三、调用示例 #### 测试代码 ```java public class TestApp { public static void main(String[] args) { try { String response = DeepSeekClient.callDeepSeekAPI( "用Java实现快速排序算法" ); System.out.println("DeepSeek响应:\n" + response); } catch (IOException e) { e.printStackTrace(); } } } ``` #### 输出示例 ``` DeepSeek响应: 以下是Java实现的快速排序算法代码: ```java public class QuickSort { public static void sort(int[] arr) { quickSort(arr, 0, arr.length - 1); } private static void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; swap(arr, i, j); } } swap(arr, i + 1, high); return i + 1; } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } ``` 时间复杂度:平均$O(n \log n)$,最坏$O(n^2)$ ``` --- ### 四、注意事项 1. **API版本** 模型标识符必须为`deepseek-chat-v3-0324`(区分大小写) 2. **请求限制** - 免费版:每分钟3次请求 - 商业版:每分钟100次请求 - 最大上下文长度:128K tokens 3. **错误处理** 建议添加重试机制(HTTP 429时等待30秒重试) 4. **最佳实践** - 敏感数据脱敏处理 - 生产环境使用连接池(如OkHttp ConnectionPool) - 添加请求超时设置 ```java new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) ``` 建议参考官方API文档获取最新参数要求[^1][^2]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值