Skip to content

Commit

Permalink
cas
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengcheng committed Jan 10, 2022
1 parent d27b49d commit f0fc125
Show file tree
Hide file tree
Showing 11 changed files with 516 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Jasyl.practice/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
Expand Down
15 changes: 15 additions & 0 deletions Jasyl.practice/src/main/java/concurrent/SyncDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package concurrent;

public class SyncDemo {

public static void main(String[] args) {
SyncDemo syncDemo = new SyncDemo();
syncDemo.test();
}

public void test() {
StringBuffer sb = new StringBuffer();
sb.append("hello").append("java");
System.out.println(sb.toString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package concurrent.completableFuture;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
* @author zhengcheng
* @date 2021/10/27 5:29 下午
*/
public class CompletableFutureTest {

public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {

CompletableFuture<String> str = CompletableFuture.supplyAsync(() -> {
return "Hello World1!";
});
System.out.println(str.get());

CompletableFuture.runAsync(() -> System.out.println("Hello World!"));

//异步回调
CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName()+"\t completableFuture2");
int i = 10/0;
return 1024;
});

completableFuture2.whenComplete((t,u)->{
System.out.println("-------t="+t);
System.out.println("-------u="+u);
}).exceptionally(f->{
System.out.println("-----exception:"+f.getMessage());
return 444;
});


CompletableFuture.supplyAsync(() -> "000")
.thenApply(s -> s.length()) // Function
.whenComplete((integer, throwable) -> System.out.println(integer));



}
}
25 changes: 25 additions & 0 deletions Jasyl.web/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>

<artifactId>Jasyl.web</artifactId>

Expand All @@ -30,5 +42,18 @@
<version>1.8.4</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.23</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.23</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
88 changes: 88 additions & 0 deletions Jasyl.web/src/test/java/base/CASTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package base;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 5)
@Fork(1)
@State(value = Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class CASTest {

/**
* 循环次数
*/
@Param(value = {"1000000", "10000000"})
private int loop;

/**
* 线程数
*/
@Param(value = {"10", "100"})
private int threadSize;

private static AtomicLong sumCas = new AtomicLong(0);
private static long sumSync = 0;
private static final Object lock = new Object();


@Benchmark
public void testCAS() throws InterruptedException {
ExecutorService executors = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(threadSize);
for (int i = 0; i < threadSize; i++) {
executors.submit(new Runnable() {
public void run() {
for (int j = 0; j < loop; j++) {
sumCas.incrementAndGet();
}
countDownLatch.countDown();
}
});
}
countDownLatch.await();
executors.shutdown();

}


@Benchmark
public void testSynchronized() throws InterruptedException {
ExecutorService executors = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(threadSize);
for (int i = 0; i < threadSize; i++) {
executors.submit(new Runnable() {
public void run() {
for (int j = 0; j < loop; j++) {
synchronized (lock) {
sumSync++;
}
}
countDownLatch.countDown();
}
});
}
countDownLatch.await();
executors.shutdown();
}

public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(CASTest.class.getSimpleName())
.result("result.json")
.resultFormat(ResultFormatType.JSON).build();
new Runner(opt).run();
}
}
123 changes: 123 additions & 0 deletions Jasyl.web/src/test/java/base/CASTest1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package base;

import org.junit.rules.Stopwatch;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class CASTest1 {


public void testCAS() throws InterruptedException, ExecutionException {
long startTime = System.currentTimeMillis();

List<Future> futures = new ArrayList<Future>();
final AtomicLong sum = new AtomicLong();
ExecutorService executors = Executors.newFixedThreadPool(100);
for (int i = 0; i < 100; i++) {
futures.add(executors.submit(new Runnable() {
public void run() {
for (int j = 0; j < 10000000; j++) {
sum.incrementAndGet();
}
}
}));
}
for (int i = 0; i < futures.size(); i++) {
try {
futures.get(i).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executors.shutdown();
long endTime = System.currentTimeMillis();
System.out.println("testCAS耗时=" + (endTime - startTime) + " || 结果=" + sum.longValue());


}


private long count = 0;

public void testSynchronized() throws InterruptedException, ExecutionException {
long startTime = System.currentTimeMillis();
List<Future> futures = new ArrayList<Future>();
final Object obj = new Object();
ExecutorService executors = Executors.newFixedThreadPool(100);
for (int i = 0; i < 100; i++) {
futures.add(executors.submit(new Runnable() {
public void run() {
synchronized (obj) {
for (int j = 0; j < 10000000; j++) {
count++;
}
}
}
}));
}

for (int i = 0; i < futures.size(); i++) {
try {
futures.get(i).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executors.shutdown();
long endTime = System.currentTimeMillis();

System.out.println("testSynchronized耗时=" + (endTime - startTime) + " || 结果=" + count);

}


public static void main(String[] args) throws Exception {

CASTest1 casTest1 = new CASTest1();
for (int i = 0; i < 100; i++) {

// casTest1.testSynchronized();
casTest1.testCAS();
}
//
// ExecutorService executors = Executors.newFixedThreadPool(5);
//
//
// for (int i = 0; i < 5; i++) {
// executors.submit(new Runnable() {
// @Override
// public void run() {
// try {
// CASTest1 casTest1 = new CASTest1();
// casTest1.testSynchronized();
// casTest1.testCAS();
//
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
// }
// });
//
// }
// TimeUnit.SECONDS.sleep(10);
// executors.shutdown();

}
}
Loading

0 comments on commit f0fc125

Please sign in to comment.