小编gau*_*tam的帖子

取消java中的未来任务

我想取消提交给ExecutorService的任务,从而允许相应的线程从队列中选择一个新任务.

现在这个问题已在这个论坛上多次回答....比如检查Thread.currentThread().interrupt()catch (InterruptedException e).但是,如果控制流跨越多种方法,那么进行这些检查会使代码变得笨拙.因此,如果可能的话,请在java中提出一些优雅的方法来实现此功能.

我面临的问题是future.cancel实际上不会取消任务.相反,它只是发送一个InterruptedException执行任务,任务的责任是标记自己完成并释放线程.

所以我所做的是,每当在执行中的任何地方抛出异常时,我必须放下下面的代码块,这显然看起来不太好!

if(e instanceof InterruptedException) {
                    throw e;
                }
Run Code Online (Sandbox Code Playgroud)

那么,如何在以下代码片段中实现此功能:

public class MonitoringInParallelExp {

        public static void main(String[] args) throws InterruptedException {
            MyClass1 myClass1 = new MyClass1();
            ExecutorService service = Executors.newFixedThreadPool(1);
            Future<String> future1 = service.submit(myClass1);
            Thread.sleep(2000);
            System.out.println("calling cancel in Main");
            future1.cancel(true);
            System.out.println("finally called cancel in Main");
            service.shutdown();
        }
    }

    class MyClass1 implements Callable<String> {
        @Override
        public String call() throws Exception {
            try{
                MyClass2 myClass2 = new MyClass2();
                myClass2.method2();
            } catch …
Run Code Online (Sandbox Code Playgroud)

java multithreading exception executorservice futuretask

5
推荐指数
1
解决办法
1916
查看次数

更改 REST API 响应中的字段名称

嗨,我是新手,所以我可能不了解高级解决方案!

因此,我想为 REST API 发送响应。所以基本上发生的事情是我从一个方法返回一个对象,然后这些对象的字段及其相应的值显示在 API 响应中。

明确地说,我们有一个类定义为

Class Sample
{
    String fruit;
    int cost;
}
Run Code Online (Sandbox Code Playgroud)

现在假设我们有一个上述类的对象(示例 abc)。我们还有一个方法如下:

@RequestMapping(/inventory)
public Sample getInventory()
{
    Sample abc = new Sample();
    ----Some processing----
    return abc;
}
Run Code Online (Sandbox Code Playgroud)

所以我得到的回应是

{
    "fruit":"apple",
    "cost":100
}
Run Code Online (Sandbox Code Playgroud)

现在我想要的是响应中的“fruit.name”,但显然我不能有具有该名称的字段(带有点或@ 字符)!

{
    "fruit.name":"apple",
    "cost@Dollars":100
}
Run Code Online (Sandbox Code Playgroud)

那么有什么方法可以帮助我得到这种回应吗?

java rest spring json spring-mvc

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

卷曲命令以获取时间

我正在运行 curl 命令:

curl -s -w "\n\n%{time_connect} + %{time_starttransfer} = %{time_total}\n\n" GET http://www.google.com
Run Code Online (Sandbox Code Playgroud)

我得到的回应是:

0.000 + 0.000 = 0.000

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.in/?gfe_rd=cr&amp;dcr=0&amp;ei=zWUAWsbbDabU-APf85KoBQ">here</A>.
</BODY></HTML>


0.217 + 0.416 = 0.417
Run Code Online (Sandbox Code Playgroud)

所以我不明白的一件事是为什么需要两个时间实例以及它们代表什么?

0.000 + 0.000 = 0.000

0.217 + 0.416 = 0.417
Run Code Online (Sandbox Code Playgroud)

linux curl http

0
推荐指数
1
解决办法
7133
查看次数