这是一种最简单实现异步的方法之一
public class sync {
public static void doSomethingA(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-------doSomethingA--------");
}
public static void doSomethingB(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("----------doSomethingB------------");
}
/**
* 使用异步的方法调用
* */
public void nsynThread() throws InterruptedException {
long start = System.currentTimeMillis();
Thread thread = new Thread(() ->{
try {
doSomethingA();
} catch (Exception e) {
e.printStackTrace();
}
},"threadA");
thread.start();
//执行任务B
doSomethingB();
//3、同步等待线程A运行之后的结果
thread.join();
System.out.println(System.currentTimeMillis()-start);
}
/**
* 开启线程进行异步执行的方式,并重写run方法
* */
public void overirideThread() throws InterruptedException {
long start = System.currentTimeMillis();
Thread thread = new Thread("threadA"){
@Override
public void run() {
try {
doSomethingA();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
//2.执行任务B
doSomethingB();
//3.同步等待线程A运行结果
thread.join();
System.out.println(System.currentTimeMillis()-start);
}
public static void main(String[] args) throws InterruptedException {
sync sync = new sync();
sync.overirideThread();
}
}
如果是同步进行的那么执行时间大概4S左右;但用异步实现的话就是那就是2S左右;
第一种是方式是实现java.lang.Runnable接口的run方式;
第二种开启了线程进行异步执行的方式是实现Thread类。并重写run方法;