小编Ste*_*eve的帖子

System.out :: println的等效lambda表达式是什么

我偶然发现了以下使用方法参考的Java代码 System.out.println

class SomeClass{
    public static void main(String[] args) {
           List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
           numbers.forEach(System.out::println);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

什么是等效的lambda表达式System.out::println

java lambda java-8 method-reference

20
推荐指数
2
解决办法
1万
查看次数

Java 模式变量作用域

我正在阅读 Oracle 的官方文档来了解Java 17 中的模式变量范围。在以下示例中,该方法testScope1按照文档中的说明工作,但该方法testScope2给出了编译错误。我无法弄清楚为什么void该方法的返回类型会导致问题?

interface Vehicle{}
class Car implements Vehicle{}

class Pattern{
    public int testScope1(Vehicle v){
        if(!(v instanceof Car c)){
            return 1;
        }
        System.out.println(c.toString());  //WORKS FINE
        return 2; 
    }
    public void testScope2(Vehicle v){
        if(!(v instanceof Car c)){
                 
        }
        System.out.println(c.toString());  //COMPILE TIME ERROR: Cannot resolve symbol c
    }
}
Run Code Online (Sandbox Code Playgroud)

java instanceof java-17

10
推荐指数
2
解决办法
1206
查看次数

具有corePoolSize 0的ThreadPoolExecutor在任务队列已满之前不应执行任务

我正在经历Java Concurrency In Practice并且陷入8.3.1线程创建和拆解主题.以下脚注警告要保持corePoolSize零.

开发人员有时会试图将核心大小设置为零,这样工作线程最终会被拆除,因此不会阻止JVM退出,但这可能会导致在不使用a的线程池中出现一些看似奇怪的行为.用于工作队列的SynchronousQueue(如newCachedThreadPool所做的那样).如果池已经是核心大小,则ThreadPoolExecutor仅在工作队列已满时才创建新线程.因此,在队列填满之前,提交给具有任何容量和核心大小为零的工作队列的线程池的任务将不会执行,这通常不是所希望的.

所以为了验证这一点,我写了这个程序,它不能像上面说的那样工作.

    final int corePoolSize = 0;
    ThreadPoolExecutor tp = new ThreadPoolExecutor(corePoolSize, 1, 5, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>());

    // If the pool is already at the core size
    if (tp.getPoolSize() == corePoolSize) {
        ExecutorService ex = tp;

        // So tasks submitted to a thread pool with a work queue that has any capacity
        // and a core size of zero will not execute until the queue fills …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading threadpool java-threads

6
推荐指数
1
解决办法
1169
查看次数

使用System.out.format和System.out.println进行多线程处理

我在Oracle的Java Tutorial中遇到了这个例子,描述了多线程场景中的死锁.

所以在这个例子中,我在第17行和第18行进行了以下更改.

public class DeadLock {
  static class Friend {
    private final String name;

    public Friend(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public synchronized void bow(Friend bower) {
        //My Changes
        //System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName()); //Line 17
         System.out.println(this.name + ": " + bower.getName() + " has bowed to me!"); //Line 18
        bower.bowBack(this);
    }

    public synchronized void bowBack(Friend bower) {
        System.out.format("%s: %s" + " has bowed …
Run Code Online (Sandbox Code Playgroud)

java multithreading deadlock println

2
推荐指数
1
解决办法
552
查看次数