java.util.current

本文介绍了Java并发编程的核心API,包括Executor、ExecutorService等接口及其使用方法,详细讲解了线程池的创建与管理,线程的启动、取消及线程间的协作方式。

JDK5中增加了Doug Lea的并发库,这一引进给java线程的管理和使用提供了强大的便利性。
java.util.current包中提供了对线程优化、管理的各项操作,使得线程的使用变得的心应手。该包提供了线程的运行,线程池的创建,线程生命周期的控制,线程间的协作等功能。

一、核心API介绍
1、
Executor接口
public void
execute(Runnable runnable);
该接口声明了execute方法,将Runnable对象传入,启动该方法相当于启动了该线程
2、ExecutorService接口
该接口是Executor的子接口,提供了submit方法,该方法返回Future对象,Future可用于控制线程的执行
与取消
3、ScheduledExecutorService接口
 该接口是ExecutorService的子接口,提供了线程启动时机的控制

 4、Callable接口
 提供了如下方法
 public Object call() throws Exception;
 该接口类似Runnable接口,只是有返回值和抛出的异常,该方法返回的值就是ExecutorService接口调用
submit(Callable
call)方法的Future调用get方法返回的值。
5、Future接口
Future接口用于控制线程的执行。调用cancell(boolean
bool)方法将会取消正在运行的进程。
另外ExecutorService的shutDown()方法将启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如  果已经关闭,则调用没有其他作用;shutDownNow()方法试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。
6、Executors
这是一个线程池的工厂类,该类提供了许多生成Executor,ExecutorService,ScheduleExecutorService的工厂方法。

 其实,Executor就相当于一个线程池,提供对线程的管理功能,包括启动线程,取消线程执行,加入线  程,移除线程,以及协调线程之间的工作等功能,这些随着Executor级别(即子接口,实现类)越高而功  能越强。
二、应用简介
1、启动一个线程
Executor executor=Executors.newFixedThreadPool(3);
executor.execute(new Runnable(){
     public void run(){
       //your code
     }
 });
也可以启动Callable形式的线程
ExecutorService executor=Executors.newFixedThreadPool(3);
executor.submit(new Callable(){
    public Object call()throws Exception{
         Object o=null;
         // your code;
         return o;
    }
});

注意,以上的方法每执行一次就运行一次Runnable或Callable对象的run(),call()方法,如果生成的Executor对象指定了数目,例如上面中是3,则当调用execute方法或submit方法时到达3次以上时,实际上同时运行的线程最多只有3个,是按照顺序的(即多出来的,后放进去的线程没有运行),只有当Executor池中正在运行的线程少于3个(即某些线程处于idle空虚状态,不在运行了),其后多出来的线程才会开始运行(按调用执行的顺序),但任何时候最多只能有3个线程运行。
同一个线程可以被执行多次,多长调用执行方法就行了。

2、取消线程的执行
当想终止线程的执行时,可以调用Future的cancell方法,但也不一定能够终止;另外如果是ExecutorSrvice,也可以调用 shutDownNow或者shutDown方法。shutDown方法将等待当前的线程执行完毕后终止所有的线程,而shutDownNow试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。

3、顺序执行线程
ExecutorService executor=Executors.newFixedThreadPool(3);
Future future=executor.submit(r1);//r1是Runnable或Callable实例
future.get();
executor.submit(r2);/r2是Runnable或Callable实例
以上代码将会使r1执行完后再执行r2,因为Future的get方法具有阻塞调用者线程的功能,执行get方法时,将会等待Future对应的线程执行完毕后才会返回结果,其会阻塞调用者线程。

4、从线程池中添加与移除线程
要移除线程,则需要ExecutorService接口的实现类ThreadPoolExecutor或其子类的方法。
在线程池中添加线程
调用execute或submit方法都可以将线程加入线程池,对同一个线程重复调用也可以,也相当于调用2个不同线程,只不过执行相同的代码。
在线程池中删除线程

public boolean remove(Runnable task)

 从执行程序的内部队列中移除此任务(如果存在),从而如果尚未开始,则其不再运行,如果已经删除则返回true


public void purge()
      尝试从工作队列移除所有已取消的 Future 任务。

5、线程的协作
利用CyclicBarrier可以协调线程的之间的运行,它允许一组线程互相等待,直到到达某个公共屏障点。
例如有一项工作需要有2个人完成,而这项工作有2个步骤,只有在执行第一个步骤只后,才可以执行第二个步骤,每一个步骤都需要2个人参与。这时可以使用CyclicBarrier了。2个人代表2个线程,如下。
class Worker implements Runnable{
    private Work work;
    private int speed;
    public Work(Work work,int speed){
         this.work=work;
         this.speed=speed;
    }
    public void run(){
        work.worked(speed);
    }
  
}
class Work {
  
    private CyclicBarrier barrier;
    public Work(CyclicBarrier barrier){
     
       this.barrier=barrier;
    }
    public void worked(int speed){
        firstWork(speed);
        secondWork();
    }
    private void firstWork(int speed){
       
        barrier.await();
        try{
        Thread.sleep(speed);
        }catch(Exception e){
        }
    }
    private void secondWork(){
       
        barrier.await();
    }
}

 public static void main(String args[]){
    CyclicBarrier barrier=new CyclicBarrier(2);
    Work work=new Work(barrier);
    Worker worker1=new Worker(work);
    Worker worker2=new Worker(work);
    Executor executor=Executors.newFixedPoolThread(2);
    executor.execute(worker1);
    executor.execute(worker2);
}

6、线程池的线程回收
CompletionService是一个管理执行完毕的线程的类,以Executor为参数构造实例。submit方法用于提交任务,似乎是委派给Executor执行,而take()方法则是获取并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等待。,pool也类似只不过当时没有时返回null并不等待。

<think>Hmm, the user is asking about the meaning of "java.base/java.util" in the context of Java modules. This seems to be a follow-up to previous discussions about JDK 17 upgrades and module system issues. The user appears to be troubleshooting Java module access problems, likely during a migration project. Given their technical focus on JVM parameters like --add-opens, they're probably a Java developer or system administrator dealing with compatibility issues. There might be some frustration behind this query since they're drilling down into specific syntax after previous solutions didn't fully resolve their problem. I should clarify that "java.base/java.util" has two parts: the module name (java.base) and the package name (java.util). This is crucial because Java's module system requires explicit permission for deep reflection across modules. The user might be confused why they need to specify both, or how this differs from regular package imports. The question indicates they're still struggling with the module system concepts. I should explain this simply but technically, emphasizing practical implications - like how this syntax directly relates to their earlier errors about inaccessible packages. Since they're clearly in problem-solving mode, I'll include troubleshooting tips about common mistakes (like mixing up module/package names) that could cause their --add-opens fixes to fail. The examples should show correct versus incorrect usage to prevent misconfiguration. For the required follow-up questions, I'll focus on adjacent pain points: module naming conventions (since java.base is special), debugging techniques when options don't work, and migration strategies - all natural extensions of their current struggle. Keeping them technical but actionable, since this user values concrete solutions. Noting that they strictly demand Chinese responses and the specific formatting rules. Must end with precisely formatted questions without line breaks - they've reinforced this requirement multiple times, suggesting they might be automating processing of these responses. </think>在 Java 模块系统中,`java.base/java.util` 是一个**模块/包路径组合**,其含义如下: 1. **`java.base`** - Java 平台最基础的模块,包含核心类(如 `java.lang`、`java.util`、`java.io` 等) - 所有 Java 模块默认依赖此模块(无需显式声明) - 在 JDK 9+ 的模块系统中具有最高封装级别 2. **`java.util`** - 属于 `java.base` 模块中的具体包(package) - 包含常用工具类(如集合框架 `ArrayList`, `HashMap`,日期处理等) 3. **组合意义** `java.base/java.util` 表示: ▸ **模块**: `java.base` ▸ **包**: `java.util` 当使用 `--add-opens java.base/java.util=ALL-UNNAMED` 时,意为: > **向未命名模块(传统类路径)开放 `java.base` 模块中 `java.util` 包的深度反射访问权限** --- ### 典型错误场景示例 ```log 错误: java.lang.reflect.InaccessibleObjectException: Unable to make field private final char[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module ``` ▸ **根源**:代码尝试反射访问 `java.lang` 包(属于 `java.base` 模块)的私有字段 ▸ **修复**:需添加 `--add-opens java.base/java.lang=ALL-UNNAMED` --- ### 关键注意事项 1. **格式必须精确** ```diff - java.util // 错误:缺少模块名 - java.base/java.util/ // 错误:多余斜杠 + java.base/java.util // 正确格式 ``` 2. **常见需开放的包** | 模块 | 包 | 用途 | |-------------|-------------------|--------------------------| | `java.base` | `java.util` | 集合类反射 | | `java.base` | `java.lang` | 字符串/类加载器操作 | | `java.base` | `java.io` | I/O 相关反射 | | `java.sql` | `java.sql` | 数据库驱动兼容 | 3. **诊断命令** ```bash java --illegal-access=warn -jar your-app.jar # 输出非法访问警告 jdeps --jdk-internals your-app.jar # 检测内部API使用 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值