Java – understanding the future / threads

I tried to use futures for the first time It looks smart. You can cancel a job, but it doesn't work as expected In the following example, only the first job is cancelled The rest is done Have I misunderstood the use of futures?

public class ThreadExample 
{
    public static void main(String[] args) throws InterruptedException,ExecutionException 
    {
        int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("Processors: " + processors);
        ExecutorService es = Executors.newFixedThreadPool(processors);
        int Nowork = 10;
        Future<Integer>[] workres = new Future[Nowork];
        for(int i = 0; i < Nowork; i++)
        {
            workres[i] = es.submit(new SomeWork(i));
        }
        for(int i = 0; i < Nowork; i++) 
        {
            if(i % 2 == 0)
            {
                System.out.println("Cancel");
                workres[i].cancel(true);
            }
            if(workres[i].isCancelled())
            {
                System.out.println(workres[i] + " is cancelled");
            }
            else
            {
                System.out.println(workres[i].get());
            }
        }
        es.shutdown();
    }
}

class SomeWork implements Callable<Integer> 
{
    private int v;
    public SomeWork(int v) 
    {
        this.v = v;
    }

    @Override
    public Integer call() throws Exception
    {
        TimeUnit.SECONDS.sleep(5);
        System.out.println(v + " done at " + (new Date()));
        return v;
    }
}

Output:

Processors: 4
Cancel
java.util.concurrent.FutureTask@10d448 is cancelled
4 done at Wed May 12 17:47:05 CEST 2010
2 done at Wed May 12 17:47:05 CEST 2010
1 done at Wed May 12 17:47:05 CEST 2010
3 done at Wed May 12 17:47:05 CEST 2010
1
Cancel
2  
3
Cancel
4
5 done at Wed May 12 17:47:10 CEST 2010
7 done at Wed May 12 17:47:10 CEST 2010
8 done at Wed May 12 17:47:10 CEST 2010
6 done at Wed May 12 17:47:10 CEST 2010  
5
Cancel
6
7
Cancel
8
9 done at Wed May 12 17:47:15 CEST 2010  
9

Solution

The problem is that your cancel loop overlaps with your get() loop and is blocked I think you want two cycles, don't you? One loop cancels even numbered jobs, then cancels the second loop, checks which have been cancelled and which are not, and then obtains the corresponding get()

The way it is written now, it even has the opportunity to cancel the work [2] before the loop. It checks and requests the get() [1] of the work

So I think you need three stages:

1. The `submit()` loop
2. The selective `cancel()` loop
3. The selective `get()` loop (which blocks)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>