线程调优案例

  • 话不多说,直接粘代码
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskTest {
    
    

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        //获取此时时间
        long start = System.currentTimeMillis();

        //调用A方法
        Callable<String> aCall = new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
                return getA();
            }
        };

        FutureTask<String> aFuture = new FutureTask<>(aCall);
        new Thread(aFuture).start();

        //调用B方法
        Callable<String> bCall = new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
                return getB();
            }
        };

        FutureTask<String> bFuture = new FutureTask<>(bCall);
        new Thread(bFuture).start();

        long end = System.currentTimeMillis();

        long l = end - start;

        System.out.println("main 执行时长为" + l + "-" + aFuture.get() + bFuture.get());
    }

    public static void main1(String[] args) {
    
    
        //获取此时时间
        long start = System.currentTimeMillis();

        //调用A方法
        String a = getA();

        //调用B方法
        String b = getB();

        long end = System.currentTimeMillis();

        long l = end - start;

        System.out.println("main 执行时长为" + l);//4010
    }

    private static String getA() {
    
    
        try {
    
    
            Thread.sleep(2000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        return "a";
    }

    private static String getB() {
    
    
        try {
    
    
            Thread.sleep(2000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        return "b";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/121622707