RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-245158

golubtsoff's questions

Martin Hope
golubtsoff
Asked: 2020-12-09 10:55:42 +0000 UTC

为什么在启动REST服务时添加FormDataParam注解会抛出异常?

  • 0

Jersey文档(版本 2.29.1)具有以下示例Example 9.50. Use of @FormDataParam annotation:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String postForm(
    @DefaultValue("true") @FormDataParam("enabled") boolean enabled,
    @FormDataParam("data") FileData bean,
    @FormDataParam("file") InputStream file,
    @FormDataParam("file") FormDataContentDisposition fileDisposition) {

    // ...
}

就我而言,该方法如下所示:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/test")
public Response saveFiles(        
    @FormDataParam("file") InputStream file,
    @FormDataParam("file") FormDataContentDisposition fileDisposition
){
    return Response.ok().build();
}

启动服务器时(也就是说,它甚至没有到达方法调用),我收到以下错误(我使用的是 Apache Tomcat / 8.5.16):

类型异常报告

servlet [rest.ApplicationConfig] 的消息 Servlet.init() 抛出异常

说明 服务器遇到了阻止它完成请求的意外情况。

例外

javax.servlet.ServletException:Servlet [rest.ApplicationConfig] 的 Servlet.init() 抛出异常 org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) ErrorReportValve.java:80) org.apache.catalina。 Valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) org. apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint. java:1455) org.apache.tomcat.util.net.SocketProcessorBase。运行(SocketProcessorBase.java:49)java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)org.apache.tomcat.util。线程.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

根本原因

java.lang.IllegalStateException:资源配置在此上下文中不可修改。org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:246) org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:193) org.glassfish.jersey.server.ResourceConfig。 register(ResourceConfig.java:426) org.glassfish.jersey.servlet.WebComponent.(WebComponent.java:306) org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:154) org.glassfish.jersey.servlet .ServletContainer.init(ServletContainer.java:346) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) org.apache.catalina.valves .ErrorReportValve.invoke(ErrorReportValve.java:80) org.apache。

注意服务器日志中提供了根本原因的完整堆栈跟踪。

同时,如果去掉@FormDataParam("file") InputStream fileand @FormDataParam("file") FormDataContentDisposition fileDisposition,则服务器正常启动:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/test")
public Response saveFiles(){
    return Response.ok().build();
}

服务器本身的配置不使用web.xml,如果这很重要:

@ApplicationPath("/")
public class ApplicationConfig extends Application {

}

像这样尝试,结果完全一样:

@ApplicationPath("/")
public class ApplicationConfig extends ResourceConfig {
    public ApplicationConfig(){            
        register(MultiPartFeature.class);
    }
}

有什么问题以及如何解决?

post
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-12-06 15:12:54 +0000 UTC

如何使用 Jersey 向正在运行的 REST 服务发送请求?

  • 0

例如,有一个 REST 资源:

 @POST    
 @Path("/test")    
 @Consumes(MediaType.APPLICATION_JSON)
 public Response create(String content){

      ...
 }

如何使用 Jersey 库在客户端中请求此资源?请求示例:

POST http://localhost:8080/test
Authorization: Basic eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjIsInJvbGUiOiJDVVNUT01FUiIsImlzcyI6ImFwcDRwcm8ucnUifQ.rPfB4I-VdJ09ca5ogD5D6c1aYUtySAYAgjW8_TefZSY
Content-Type: application/json

*json content*
java-ee
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-11-11 10:40:52 +0000 UTC

如何将选定的下拉值传递给 Thymeleaf 中的控制器?

  • 1

请帮我将选定的下拉值(Thymeleaf)传递给控制器​​(Spring)。有一个控制器:

@RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (@RequestParam String task) {
    System.out.println(task);
    return "redirect:/courier";
}

这是一个带有按钮的列表(它不能正常工作):

<div class="taskList" th:object="${task}">
    <select class="form-control" id="courierTasks" name="courierTasks">
        <option value="">Select task for disable</option>
        <option th:each="task : ${tasks}"
                th:value="${task}"
                th:text="${task}">
        </option>
    </select>
    <form th:action="@{/courier/notInTime}" method="post">
        <input type="hidden"/>
        <button type="submit">Not in time</button>
    </form>
</div>

列表本身形成正常,问题出在按钮上。如何将列表中选择的值传递给它并发送给控制器?

spring
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-10-21 20:15:06 +0000 UTC

如何使用 SQL 按列计算总和?

  • 0

请帮助计算下表的列总和的 SQL 查询,cost按以下方式分组:sale_idmy_data

id      cost     sale_id   customer_id
---------------------------------------
14030   1736.00     15      1389
14031   1685.00     21      1389
14032   1546.00     21      1389
14033   1233.00     15      1389
14034   1719.00     18      1390
14035   1164.00     19      1390
14036   1736.00     14      1390
14037   1685.00     21      1390
14038   1233.00     14      1390
14039   1546.00     23      1390
14040   1719.00     18      1390
14041   1719.00     18      1390
14042   1719.00     18      1390
14043   1719.00     18      1390
14044   1719.00     18      1390
14045   1090.00     16      1391
14046   1233.00     14      1391
14047   1736.00     15      1391
14048   1685.00     21      1391
14049   1546.00     23      1391
14050   1090.00     16      1391
14051   1090.00     18      1391
14052   1090.00     18      1391
14053   1090.00     18      1391
14054   1090.00     16      1391
14055   1090.00     16      1391

有以下细微差别:在同一个中,只考虑第一次customer_id出现。例如,仅考虑以下 id:14034、14051。字段总和为 1719 + 1090 = 2809。 结果应如下所示:costsale_idsale_id = 18cost

sale_id     sum
--------------------
15          3472
21          5055
18          2809
19          1164
14          2969
23          3092
16          1090
sql
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-09-07 12:50:26 +0000 UTC

如何在不执行 Intellij Idea 中的进一步代码的情况下中断调试?

  • 1

在 Intellij Idea Ultimate 中,我在调试模式下运行以下代码:

public class Main {

    public static void main(String[] args) {
        System.out.println("Это не должно отображаться");
    }
}

我在行上放了一个断点System.out.println("Это не должно отображаться");。在调试模式下运行后,执行将在断点所在的行处停止。如果您现在单击 IDE 中的停止按钮(即停止调试),那么控制台中将出现“这不应该显示”行。按下停止时不应该中断进一步的执行吗?在版本 2017.3.5 和 2019.2.2(当前为当前版本)中观察到该问题。

java
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-05-04 11:32:48 +0000 UTC

是否可以在不直接计算的情况下评估大数乘积的结果?

  • 0

在 7-8 年级的奥林匹克题中,使用了序号10^18。数字本身在范围内long long (_int64)。在求解的过程中,您必须将两个相似尺寸的数字相乘,并将相似的产品相互比较。

也就是说,产品的结果可以是订单数10^36,并且这些结果必须相互比较。考虑到这是奥林匹克竞赛,我认为那里不允许使用第三方库来处理大量数据,而且从参与者的年龄来看,他们自己不太可能需要编写函数来处理有大量数字。

是否可以在不直接计算的情况下评估产品的结果,并将它们相互比较?

UPD。按要求Alexey Ten附上问题的扫描件 。在此处输入图像描述

c++
  • 2 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-03-10 12:09:24 +0000 UTC

如何在“未经检查的分配”上强制转换参数化类型?

  • -1

如何在以下函数中正确键入 cast:

public static <T> Dao<T> getDao(Class<T> cl){
    for(Dao dao : daoList){
        if (cl == dao.getParameterizedClass())
            return dao;
    }
    return null;
}

事实上,在该行中,return dao该词dao被突出显示并出现警告Unchecked assignment: 'dao.Dao' to 'dao.Dao<T>。

这是包含此函数的类的样子:

public abstract class DaoFactory {

    private static final List<Dao<?>> daoList = Arrays.asList(
            new DaoImpl<>(Person.class)    
    );

    public static <T> Dao<T> getDao(Class<T> cl){
        for(Dao dao : daoList){
            if (cl == dao.getParameterizedClass())
                return dao;
        }
        return null;
    }
}

这是 Dao 接口:

public interface Dao<T> {  
    Class<T> getParameterizedClass();
}

及其实施:

public class DaoImpl<T> implements Dao<T> {

    private Class<T> parameterizedClass;

    DaoImpl(Class<T> cl){
        this.parameterizedClass = cl;
    }

    @Override
    public Class<T> getParameterizedClass() {
        return parameterizedClass;
    }
}

当然,您可以抑制警告,或者使返回类型不参数化 - 不是Dao<T>,而只是Dao。还有其他方法可以解决警告吗?

java
  • 2 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-03-06 10:01:39 +0000 UTC

如何删除 jsp 文件的“a href”标签中的“无法解析文件”警告?

  • 0

你能告诉我为什么分析器a href = ссылка对jsp文件中的链接()的值给出警告吗?例如:

<c:forEach items="${items}" var="item">
            <jsp:useBean id="item" type="entity.Item"/>
            <tr>
                <td><a href="item?id=${item.id}&action=view">${item.title}</a></td>                    
                <td><%=CurrencyFormat.format(item.getPrice())%></td>
                <c:if test="${role == 'admin'}">                        
                    <td>${item.amount}</td>
                    <td><a href="item?id=${item.id}&action=delete">Delete</a></td>
                    <td><a href="item?id=${item.id}&action=edit">Edit</a></td>
                </c:if>
                <c:if test="${role == 'user'}">
                    <td><a href="item?id=${item.id}&action=buy">Buy</a></td>
                </c:if>
            </tr>
</c:forEach>

<a href="item?id...在这里,该词在线条中带有下划线item并发出警告Cannot resolve file 'item'。应用程序编译并成功运行。如何在不禁用或抑制检查的情况下解决警告?

java
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-03-05 15:58:49 +0000 UTC

如何修复 HQL 查询中的“无法解析符号”错误?

  • 0

请帮我修复以下方法中的错误:

public List<Item> getAll() {
    return DBService.getSessionFactory()
        .getCurrentSession()
        .createQuery("from Item", Item.class)
        .list();
}

代码编译得很好,但静态分析器在表达式中的"from Item"单词下划线Item并写入Can't resolve symbol 'Item'. 由 Intellij IDEA 使用。如果Project Structure -> Facets添加 JPA,则此警告会消失。但是另一个警告出现在用 注释的类@Entity中,例如:

@Entity
@Table(name = "items")
public class Item {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
...
}

在该行中,@Table(name = "items")分析器会在单词下划线items并出现警告Cannot resolve table 'items'。字符串也是如此。@Column(name = "ID")这里的单词有下划线"ID"。编译成功,应用程序工作正常。应该怎么做才能消除分析仪警告?

java
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-09-23 19:53:08 +0000 UTC

如何避免 C 中的代码重复

  • 0

假设我们有以下数据结构:

enum Color{
    Red,
    Blue,
    Black,
    White
};

struct Car{
    char* model;
    enum Color color;
    double engineCapacity;
};

struct Cars{
    struct Car *garage;
    size_t count;
};

有两个函数可以在类型列表中查找具有匹配字段的元素color:engineCapacityCars

struct Car *findByColor(struct Cars cars, enum Color color){
    while(cars.count-- > 0){
        if (cars.garage->color == color){
            return cars.garage;
        }
        cars.garage++;
    }
    return NULL;
}

struct Car *findByEngineCapacity(struct Cars cars, double engineCapacity){
    while(cars.count-- > 0){
        if (cars.garage->engineCapacity == engineCapacity){
            return cars.garage;
        }
        cars.garage++;
    }
    return NULL;
}

可以看出,功能几乎是相互重复的。你能告诉我在这种情况下如何避免代码重复吗?

c
  • 3 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-08-28 10:55:18 +0000 UTC

从文件中读取数据的通用方法

  • 4

你好。告诉我如何编写一个从文件中读取数据的通用方法。例如,在一种情况下,您需要计算字符串,在另一种情况下需要计算整数。如何编写这样的方法:

    public static <T> List<T> readFromFile(Path pathIn, TypeValue typeValue){...};

此代码是否正确:

public static List readFromFile(Path pathIn, TypeValue typeValue){
        try(Scanner in = new Scanner(pathIn)) {
            if (typeValue == TypeValue.typeInt) {
                List<Integer> list = new ArrayList<>();
                while (in.hasNextInt()) {
                    list.add(in.nextInt());
                }
                return list;
            } else {
                List<String> list = Files.readAllLines(pathIn);
                return list;
            }
        } catch (IOException e){ 
            return null;
        }
    }

这里pathIn- 数据文件的路径,typeValue- 指定数据的标志(Integer等String)。令人困惑的是它返回一个未参数化的List. 如果数据格式可以不同 - Integer,等Double,通常如何解决从文件读取的任务String?还是应该编写自己的代码来读取每种数据类型?那就有点麻烦了。

java
  • 2 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-08-11 11:52:50 +0000 UTC

JUnit 和 Nan 中的参数化测试

  • 1

你好。告诉我当被测函数产生不同类型的结果时如何正确处理测试。比如有这样一个测试类:

public class Calculator {    

    public Double leg(int hyp, int leg){
        if (Math.abs(hyp) < Math.abs(leg))
            return Double.NaN;
        return Math.sqrt(Math.pow(hyp, 2) - Math.pow(leg, 2));
    }
}

这是测试类:

import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.*;

@RunWith(Parameterized.class)
public class CalculatorParametrizedTest {
    public Calculator calculator;
    private int hyp;
    private int leg;
    private double expected;

    @Parameterized.Parameters(name = "Тест {index}: гипотенуза = {0}, катет = {1}, катет = {2}")
    public static Iterable<Object[]> dataForTest() {
        return Arrays.asList(new Object[][]{
                {5, 4, 3},
                {5, -4, 3},
                {-5, 4, 3},
                {-5, -4, 3},
                {4, 5, Double.NaN},
                {3, 2, 2.24}
        });
    }

    public CalculatorParametrizedTest(int hyp, int leg, double expected){
        this.hyp = hyp;
        this.leg = leg;
        this.expected = expected;
    }

    @Before
    public void setUp(){
        calculator = new Calculator();
    }

    @After
    public void tearDown(){
        calculator = null;
    }

    @Test
    public void testLeg(){
        assertThat(calculator.leg(hyp, leg), is(closeTo(expected, 0.1)));
    }
}

使用 value 测试失败{4, 5, Double.NaN}。这是错误的描述:

java.lang.AssertionError: Expected: is a numeric value within <0.1> of but:<NaN>不同<NaN>

我知道比较 NaN 和 NaN 是没有意义的,但我不明白如何正确编写测试。如何为示例中给出的函数编写测试leg?

java
  • 1 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-07-17 09:06:18 +0000 UTC

Spring中带参数的构造函数

  • 1

你好。请告诉我如何通过带参数的构造函数创建 bean。例如,有这样一个类(两个构造函数——空的和带参数的;为简洁起见,不给出getter、setter):

import java.time.LocalDateTime;

public class Route {
    private LocalDateTime arrive;
    private LocalDateTime departure;
    private String from;
    private String to;

    public Route(){}

    public Route(LocalDateTime arrive, LocalDateTime departure, String from, String to) {
        this.arrive = arrive;
        this.departure = departure;
        this.from = from;
        this.to = to;
    }

    // геттеры, сеттеры

    public void printRoute(){
        System.out.println("Откуда: " + from +
        ", куда: " + to +
        ", прибытие: " + arrive +
        ", отбытие: " + departure);
    }
}

主要类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class TrainScheduleApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");
        Route route = ctx.getBean("routeEmpty", Route.class);
        route.printRoute();
    }
}

文件“app-context.xml”:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans [url]http://www.springframework.org/schema/beans/spring-beans.xsd[/url]
        [url]http://www.springframework.org/schema/context[/url] http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <bean id="routeEmpty" class="com.example.demo.Route">
    </bean>

</beans>

其实问题是这样的:

  • 如何使用带有类型参数的构造函数创建路由(Route)LocalDateTime;
  • 如何通过将必要的参数传递给构造函数来创建不同的路由(垃圾箱);即,让参数不写在xml文件中(那么所有路由创建的都是一样的),但是可以从代码中动态传递必要的参数(类似Route route = new Route(arrive, departure, from, to))。

我将不胜感激。

java
  • 2 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-05-11 08:54:09 +0000 UTC

使用 Stream API 对分组数据元素进行计数

  • 1

你好。请帮忙完成以下任务。有一个 类型的数据流Person。这是类描述:

public class Person {
    private String lastname;
    private String city;
    public String getLastname() {return lastname;}
    public String getCity() {return city;}
}

您需要按城市 ( city) 对流量数据进行分组,并统计每个城市的居民人数 ( Person)。用 解决Stream API。

据我了解,结果应该是这样的Map<String, Long>。到目前为止,只能获取Person每个城市的类型列表,即Map<String, List<Person>>

public static void main(String[] args){
    List<Person> persons = new ArrayList<>();
    Map<String, List<Person>> map = persons.stream()
            .collect(Collectors.groupingBy(Person::getCity));
}

如何获得Map<String, Long>?

java
  • 2 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-04-25 17:41:07 +0000 UTC

在 Java 中使用 Stream 查找最大元素

  • 1

你好。任务是找到列表中的最大元素。请告诉我为什么以下代码不能正常工作:

import java.util.*;

public class Main {

    public static void main(String[] args){
        List<Integer> list = new ArrayList<>();
        list.add(847);
        list.add(271);
        list.add(879);
        System.out.println(maxElem(list));
    }

    public static Integer maxElem(List<Integer> list){
        Integer max = list.stream()                    
                .max(Math::max)
                .get();
        return max;
    }
}

结果不是预期的 879,而是 847。为什么?

更新。评论详细解释了为什么代码不能正常工作。我不会重复自己,我只会给出正确代码的不同版本。

Integer max = list.stream().reduce(Integer::max).get();
Integer max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
Integer max = list.stream().mapToInt(Integer::intValue).max().getAsInt();    
Integer max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();    
Integer max = list.stream().max(Comparator.naturalOrder()).get();
Integer max = list.stream().max(Integer::compare).get();
Integer max = list.stream().max((a, b) -> {
    if (a > b) return 1;
    else if (a < b) return -1;
    else return 0;
}).get();
java
  • 4 个回答
  • 10 Views
Martin Hope
golubtsoff
Asked: 2020-04-11 08:25:27 +0000 UTC

从 Java 中的多个线程更改原子值

  • 5

你好。请帮我解决以下问题:

使用 LongAccumulator 类计算最大和最小累加器。

假设应该有几个线程,生成元素的类型是任意的。这是我的代码:

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;

public class Main {
    public static LongAccumulator maxValue = new LongAccumulator(Math::max, Integer.MIN_VALUE);
    public static LongAccumulator minValue = new LongAccumulator(Math::min, Integer.MAX_VALUE);

    public static void main(String[] args){
        Random random = new Random();
//        Executor executor = Executors.newCachedThreadPool();
        Executor executor = Executors.newFixedThreadPool(1);
        for (int i = 1; i <= 1000; i++) {
            int taskId = i;
            Runnable task = () -> {
                for (int k = 1; k <= 100_000; k++){
                    int value = random.nextInt(1_000_000);
                    maxValue.accumulate(value);
                    minValue.accumulate(value);
                }
                System.out.println(taskId + ": min " + minValue.get() + ": max " + maxValue.get());
            };
            executor.execute(task);
        }
    }
}

一切正常,但并不像我预期的那样。如果所有任务都放在一个线程中(见第 1 行Executor executor = Executors.newFixedThreadPool(1);),那么一切都会或多或少地完成。如果我们代替这一行Executor executor = Executors.newCachedThreadPool();,或放置多个线程:Executor executor = Executors.newFixedThreadPool(5);,那么代码运行时间会长几倍。实际上,问题在于为什么会出现这种情况,以及如何做到将任务划分为线程不会增加程序运行时间,而是会减少程序运行时间。

更新。按照评论中给出的建议,我将代码更改如下,程序开始在多线程模式下运行得更快:

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;

public class Main {
    public static LongAccumulator maxValue = new LongAccumulator(Math::max, Integer.MIN_VALUE);
    public static LongAccumulator minValue = new LongAccumulator(Math::min, Integer.MAX_VALUE);

    public static void main(String[] args){
        Executor executor = Executors.newCachedThreadPool();
        Runnable task; // вынес объявление из цикла ниже
        for (int i = 1; i <= 1000; i++) {
            Random random = new Random();  // для каждой задачи создаётся свой Random
            int taskId = i;
            task = () -> {
                for (int k = 1; k <= 100_000; k++){
                    int value = random.nextInt(1_000_000);
                    maxValue.accumulate(value);
                    minValue.accumulate(value);
                }
                System.out.println(taskId + ": min " + minValue.get() + ": max " + maxValue.get());
            };
            executor.execute(task);
        }
    }
}
java
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5