还在Demo,大家先略过
关于Java同步:锁机制
class threadMainOne {
public static int len = 0;
public static final Object lock = new Object();
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(()->{
for (int i=0; i<10000; i++) {
threadMainOne.len += 1;
}
});
Thread t2 = new Thread(()->{
for (int i=0; i<10000; i++) {
threadMainOne.len -= 1;
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("result "+len);
}
}
关于CompletableFuture
class threadMain {
public static int len = 1;
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> resultOfComputeZero = CompletableFuture.supplyAsync(()->{
for (int i = 0; i < 100; i++) {
len++;
if(i/10==0) System.out.println("resultOfComputeZero: "+len);
}
return len;
});
CompletableFuture<Integer> resultOfComputeOne = CompletableFuture.supplyAsync(()-> {
for (int i = 0; i < 100; i++) {
len--;
if(i/10==0) System.out.println("resultOfComputeOne: "+len);
}
return len;
});
CompletableFuture<Object> result1 = CompletableFuture.anyOf(resultOfComputeZero,resultOfComputeOne);
System.out.println("result1: "+len);
CompletableFuture<Integer> resultOne = resultOfComputeZero.thenApplyAsync((s)->{
System.out.println("resultOne: "+len);
return len;
});
CompletableFuture<Integer> resultTwo = resultOfComputeOne.thenApplyAsync((s)->{
System.out.println("resultTwo: "+len);
return len;
});
System.out.println("result2: "+len);
Thread.sleep(200);
}