diff --git a/res/guava-20.0.jar b/res/guava-20.0.jar new file mode 100644 index 00000000..632772f3 Binary files /dev/null and b/res/guava-20.0.jar differ diff --git a/res/nashorn1-modified.js b/res/nashorn1-modified.js new file mode 100644 index 00000000..eafad136 --- /dev/null +++ b/res/nashorn1-modified.js @@ -0,0 +1,9 @@ +var fun1 = function(name) { + print('Hi there from Javascript, ' + name); + return "greetings from javascript"; +}; + +var fun2 = function (object) { + print("JS Class Definition: " + Object.prototype.toString.call(object)); +}; +print('foobar'); diff --git a/res/output.js b/res/output.js new file mode 100644 index 00000000..e79d7130 --- /dev/null +++ b/res/output.js @@ -0,0 +1 @@ +print('Hello World'); \ No newline at end of file diff --git a/src/com/winterbe/git/GitCommitShowCase.java b/src/com/winterbe/git/GitCommitShowCase.java new file mode 100644 index 00000000..5cceac8c --- /dev/null +++ b/src/com/winterbe/git/GitCommitShowCase.java @@ -0,0 +1,13 @@ +package com.winterbe.git; + +/** + * 类名 :GitCommitShowCase + * 项目名称 :java8-tutorial + * 创建时间 :2016/12/30 + * 作 者:sd-wangtaicheng@sdcncsi.com.cn + * 版 本:v1 + */ +public class GitCommitShowCase { + +// commit_2 +} diff --git a/src/com/winterbe/git/Test1.java b/src/com/winterbe/git/Test1.java new file mode 100644 index 00000000..c654cb71 --- /dev/null +++ b/src/com/winterbe/git/Test1.java @@ -0,0 +1,90 @@ +package com.winterbe.git; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + * @date 2018/3/29 + */ +public class Test1 { + static Connection conn = null; + + public static void main(String[] args) { + init(); + fun("0", 1, 1, 1); + } + + public static void init() { + String url = "jdbc:mysql://10.0.210.98:3309/wtc_html?useUnicode=true&characterEncoding=utf8" + + "&characterSetResults" + + "=utf8&tinyInt1isBit=false"; + String driverClass = "com.mysql.jdbc.Driver"; + String username = "mysql"; + String password = "hr123!@#"; + Statement ps = null; + try { + Class.forName(driverClass); + conn = DriverManager.getConnection(url, username, password); + conn.setAutoCommit(false); + } catch (Exception e) { + e.printStackTrace(); + + } + } + + public static void fun(String id, int l, int m, int r) { + + List> list = query(id); + + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + Map map = list.get(i); + String pid = map.get("id"); + fun(pid, l, m, r); + System.out.println(String.format("id=%s,l=%s,m=%s,r=%s", id, l, m, r)); + } + } else { + System.out.println(String.format("id=%s,l=%s,m=%s,r=%s", id, l, m, r)); + // update(id,l,m,r); + } + } + + public static List> query(String id) { + try { + String sql = "select id,pid from demo1 where pid=" + id; + Statement ps = conn.createStatement(); + ResultSet rs = ps.executeQuery(sql); + List> list = new ArrayList<>(); + if (rs != null) { + while (rs.next()) { + Map m = new HashMap<>(); + m.put("id", rs.getString("id")); + m.put("pid", rs.getString("pid")); + list.add(m); + } + } + return list; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void update(String id, int l, int m, int r) { + try { + String sql = String.format("update demo1 set l=%s,m=%s,r=%s where pid=%s", l, m, r, id); + Statement ps = conn.createStatement(); + ps.executeUpdate(sql); + } catch (Exception e) { + + } + + } +} diff --git a/src/com/winterbe/git/git1 b/src/com/winterbe/git/git1 new file mode 100644 index 00000000..e69de29b diff --git a/src/com/winterbe/git/gitd b/src/com/winterbe/git/gitd new file mode 100644 index 00000000..e69de29b diff --git a/src/com/winterbe/java8/samples/concurrent/Atomic1.java b/src/com/winterbe/java8/samples/concurrent/Atomic1.java index 0f9d3cba..11b82f7c 100644 --- a/src/com/winterbe/java8/samples/concurrent/Atomic1.java +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -40,7 +40,7 @@ private static void testUpdate() { private static void testAccumulate() { atomicInt.set(0); - ExecutorService executor = Executors.newFixedThreadPool(2); + ExecutorService executor = Executors.newFixedThreadPool(4); IntStream.range(0, NUM_INCREMENTS) .forEach(i -> { diff --git a/src/com/winterbe/java8/samples/concurrent/CallableFuture1.java b/src/com/winterbe/java8/samples/concurrent/CallableFuture1.java new file mode 100644 index 00000000..5eea2f3c --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/CallableFuture1.java @@ -0,0 +1,50 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.*; + +/** + * 类名 :CallableFuture1 + * 项目名称 :java8-tutorial + * 创建时间 :2017/5/2 + * 作 者:sd-wangtaicheng@sdcncsi.com.cn + * 版 本:v1 + */ +public class CallableFuture1 { + public static void main(String[] args) { + ExecutorService executor = Executors.newCachedThreadPool(); + Task task = new Task(); + Future result = executor.submit(task); + executor.shutdown(); + + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + + System.out.println("主线程在执行任务"); + + try { + System.out.println("task运行结果" + result.get()); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + + System.out.println("所有任务执行完毕"); + } +} + +class Task implements Callable { + @Override + public Integer call() throws Exception { + System.out.println("子线程在进行计算"); + Thread.sleep(3000); + int sum = 0; + for (int i = 0; i < 100; i++) + sum += i; + return sum; + } +} + diff --git a/src/com/winterbe/java8/samples/concurrent/CallableFuture2.java b/src/com/winterbe/java8/samples/concurrent/CallableFuture2.java new file mode 100644 index 00000000..bcd41089 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/CallableFuture2.java @@ -0,0 +1,46 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.*; + +/** + * 类名 :CallableFuture2 + * 项目名称 :java8-tutorial + * 创建时间 :2017/5/2 + * 作 者:sd-wangtaicheng@sdcncsi.com.cn + * 版 本:v1 + */ +public class CallableFuture2 { + public static void main(String[] args) { + //第一种方式 + ExecutorService executor = Executors.newCachedThreadPool(); + Task task = new Task(); + FutureTask futureTask = new FutureTask(task); + executor.submit(futureTask); + executor.shutdown(); + + //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread + /*Task task = new Task(); + FutureTask futureTask = new FutureTask(task); + Thread thread = new Thread(futureTask); + thread.start();*/ + + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + + System.out.println("主线程在执行任务"); + + try { + System.out.println("task运行结果" + futureTask.get()); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + + System.out.println("所有任务执行完毕"); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/CompletableFuture2.java b/src/com/winterbe/java8/samples/concurrent/CompletableFuture2.java new file mode 100644 index 00000000..63e2e3e0 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/CompletableFuture2.java @@ -0,0 +1,90 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ForkJoinPool; +import java.util.function.Supplier; +import java.util.stream.IntStream; + +import static java.lang.String.format; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + * @since 2019/1/14 + */ +public class CompletableFuture2 { + private static int PROCESSORS = Runtime.getRuntime().availableProcessors(); + + public static void main(String[] args) { + System.out.println("Processors: " + PROCESSORS); + + Arrays.asList(-3, -1, 0, 1, 2, 4, 5, 10, 16, 17).forEach(offset -> { + int jobNum = PROCESSORS + offset; + System.out.println( + format("When %s tasks => stream: %s, parallelStream: %s, future default: %s, future custom: %s", + jobNum, testStream(jobNum), testParallelStream(jobNum), + testCompletableFutureDefaultExecutor(jobNum), testCompletableFutureCustomExecutor(jobNum))); + }); + + } + + private static long testStream(int jobCount) { + List> tasks = new ArrayList<>(); + IntStream.rangeClosed(1, jobCount).forEach(value -> tasks.add(CompletableFuture2::getJob)); + + long start = System.currentTimeMillis(); + int sum = tasks.stream().map(Supplier::get).mapToInt(Integer::intValue).sum(); + checkSum(sum, jobCount); + return System.currentTimeMillis() - start; + } + + private static long testParallelStream(int jobCount) { + List> tasks = new ArrayList<>(); + IntStream.rangeClosed(1, jobCount).forEach(value -> tasks.add(CompletableFuture2::getJob)); + + long start = System.currentTimeMillis(); + int sum = tasks.parallelStream().map(Supplier::get).mapToInt(Integer::intValue).sum(); + checkSum(sum, jobCount); + return System.currentTimeMillis() - start; + } + + private static long testCompletableFutureDefaultExecutor(int jobCount) { + List> tasks = new ArrayList<>(); + IntStream.rangeClosed(1, jobCount).forEach(value -> tasks.add(CompletableFuture.supplyAsync(CompletableFuture2::getJob))); + + long start = System.currentTimeMillis(); + int sum = tasks.stream().map(CompletableFuture::join).mapToInt(Integer::intValue).sum(); + checkSum(sum, jobCount); + return System.currentTimeMillis() - start; + } + + private static long testCompletableFutureCustomExecutor(int jobCount) { + Executor executor = new ForkJoinPool(20); + + List> tasks = new ArrayList<>(); + IntStream.rangeClosed(1, jobCount).forEach(value -> tasks.add(CompletableFuture.supplyAsync(CompletableFuture2::getJob, executor))); + + long start = System.currentTimeMillis(); + int sum = tasks.stream().map(CompletableFuture::join).mapToInt(Integer::intValue).sum(); + checkSum(sum, jobCount); + return System.currentTimeMillis() - start; + } + + private static int getJob() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + + return 50; + } + + private static void checkSum(int sum, int jobNum) { + if (sum != 50 * jobNum) { + throw new AssertionError("Result Error"); + } + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java index 4acf79ab..234165ae 100644 --- a/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java @@ -11,9 +11,9 @@ public class ConcurrentHashMap1 { public static void main(String[] args) { System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism()); - testForEach(); + //testForEach(); testSearch(); - testReduce(); + //testReduce(); } private static void testReduce() { @@ -69,7 +69,7 @@ private static void testForEach() { map.putIfAbsent("c3", "p0"); map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); -// map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); + //map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); System.out.println(map.mappingCount()); } diff --git a/src/com/winterbe/java8/samples/concurrent/ConditionDemo.java b/src/com/winterbe/java8/samples/concurrent/ConditionDemo.java new file mode 100644 index 00000000..d4cf1b88 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/ConditionDemo.java @@ -0,0 +1,65 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class ConditionDemo { + volatile int key = 0; + Lock l = new ReentrantLock(); + Condition c = l.newCondition(); + + public static void main(String[] args) { + ConditionDemo demo = new ConditionDemo(); + new Thread(demo.new A()).start(); + new Thread(demo.new B()).start(); + } + + class A implements Runnable { + @Override + public void run() { + int i = 10; + while (i > 0) { + l.lock(); + try { + if (key == 1) { + System.out.println("A is Running"); + System.out.println("A is Running"); + i--; + key = 0; + c.signal(); + } else { + c.awaitUninterruptibly(); + } + + } finally { + l.unlock(); + } + } + } + + } + + class B implements Runnable { + @Override + public void run() { + int i = 10; + while (i > 0) { + l.lock(); + try { + if (key == 0) { + System.out.println("B is Running"); + i--; + key = 1; + c.signal(); + } else { + c.awaitUninterruptibly(); + } + + } finally { + l.unlock(); + } + } + } + } +} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/concurrent/CountDownLatchDemo.java b/src/com/winterbe/java8/samples/concurrent/CountDownLatchDemo.java new file mode 100644 index 00000000..fa64ff40 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/CountDownLatchDemo.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019, SDCNCSI. All rights reserved. + */ + +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.CountDownLatch; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + */ +public class CountDownLatchDemo { + public static CountDownLatch countDownLatch = new CountDownLatch(5); + + static class ThreadDemo extends Thread { + @Override + public void run() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println(Thread.currentThread().getId() + "完成任务"); + countDownLatch.countDown(); + } + } + + public static void main(String[] args) throws InterruptedException { + for (int i = 0; i < 5; i++) { + new ThreadDemo().start(); + } + countDownLatch.await(); + System.out.println("全部完成任务"); + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/CyclicBarrierDemo.java b/src/com/winterbe/java8/samples/concurrent/CyclicBarrierDemo.java new file mode 100644 index 00000000..de27669d --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/CyclicBarrierDemo.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019, SDCNCSI. All rights reserved. + */ + +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + */ +public class CyclicBarrierDemo { + public static CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new FinallyThreadDemo()); + + static class ThreadDemo extends Thread { + @Override + public void run() { + try { + Thread.sleep(1000); + System.out.println(Thread.currentThread().getId() + "完成任务"); + cyclicBarrier.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + System.out.println("到达屏障点每个线程都会瞬时继续执行"); + } + } + + static class FinallyThreadDemo extends Thread { + @Override + public void run() { + System.out.println("所有任务已经完成之后单独执行的任务!"); + } + } + + public static void main(String[] args) throws InterruptedException { + for (int i = 0; i < 10; i++) { + new ThreadDemo().start(); + } + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/Executors4.java b/src/com/winterbe/java8/samples/concurrent/Executors4.java new file mode 100644 index 00000000..90820e40 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Executors4.java @@ -0,0 +1,88 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 类名 :Executors4 + * 项目名称 :java8-tutorial + * 创建时间 :2017/5/2 + * 作 者:sd-wangtaicheng@sdcncsi.com.cn + * 版 本:v1 + */ +public class Executors4 { + + public static void main(String[] args) { +// Executors4.newCachedThreadPoolCase(); + Executors4.newFixedThreadPoolCase(); + } + + public static void newCachedThreadPoolCase() { + ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); + for (int i = 0; i < 10; i++) { + final int index = i; + try { + Thread.sleep(index * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + cachedThreadPool.execute(() -> System.out.println(index)); + } + } + + public static void newFixedThreadPoolCase() { + ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); + final AtomicInteger thread = new AtomicInteger(); + for (int i = 0; i < 10; i++) { + final int index = i; + + fixedThreadPool.execute(() -> { + try { + thread.incrementAndGet(); + System.out.println(thread.get()); + Thread.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + ); + } + while (thread.get() <10) { + try { + Thread.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public static void newScheduledThreadPoolCase() { + ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); + scheduledThreadPool.schedule(() -> + System.out.println("delay 3 seconds") + , 3, TimeUnit.SECONDS); + scheduledThreadPool.scheduleAtFixedRate(() -> + System.out.println("delay 3 seconds") + , 1, 3, TimeUnit.SECONDS); + } + + public static void newSingleThreadExecutorCase() { + ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); + for (int i = 0; i < 10; i++) { + final int index = i; + singleThreadExecutor.execute(() -> { + try { + System.out.println(index); + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + ); + } + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/Localthread1.java b/src/com/winterbe/java8/samples/concurrent/Localthread1.java new file mode 100644 index 00000000..8caed6cc --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Localthread1.java @@ -0,0 +1,50 @@ +package com.winterbe.java8.samples.concurrent; + +/** + * Created by 王太成 on 2016/9/23. + */ +public class Localthread1 { + private static ThreadLocal threadLocal = new ThreadLocal() { + protected Integer initialValue() { + return 0; + } + }; + private static ThreadLocal threadLocal1 =ThreadLocal.withInitial(()-> 0); + public static void main(String[] args) { + try { + plus(); + plusWithLam(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void plus() throws Exception { + for (int i = 0; i < 100; i++) { + new Thread() { + public void run() { + //1 + int a = threadLocal.get(); + a++; + + //2 + threadLocal.set(a); + System.out.println("plus:" + Thread.currentThread().getName() + ": " + threadLocal.get()); + } + }.start(); + } + } + private static void plusWithLam() throws Exception { + for (int i = 0; i < 100; i++) { + new Thread( ()-> { + //1 + int a = threadLocal1.get(); + a++; + + //2 + threadLocal1.set(a); + System.out.println("plusLam:" + Thread.currentThread().getName() + ": " + threadLocal1.get()); + }).start(); + } + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/LockSupportThreadDemo.java b/src/com/winterbe/java8/samples/concurrent/LockSupportThreadDemo.java new file mode 100644 index 00000000..6da20965 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/LockSupportThreadDemo.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019, SDCNCSI. All rights reserved. + */ + +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.locks.LockSupport; + +public class LockSupportThreadDemo { + public static Thread thread; + static class WaitThreadDemo extends Thread { + @Override + public void run() { + System.out.println("WaitThread wait,time=" + System.currentTimeMillis()); + thread = Thread.currentThread(); + LockSupport.park(); + System.out.println("WaitThread end,time=" + System.currentTimeMillis()); + } + } + static class NotifyThreadDemo extends Thread { + @Override + public void run() { + System.out.println("NotifyThread notify,time=" + System.currentTimeMillis()); + LockSupport.unpark(thread); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("NotifyThread end,time=" + System.currentTimeMillis()); + } + } + public static void main(String[] args) { + WaitThreadDemo waitThreadDemo = new WaitThreadDemo(); + NotifyThreadDemo notifyThreadDemo = new NotifyThreadDemo(); + waitThreadDemo.start(); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + notifyThreadDemo.start(); + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lockers.java b/src/com/winterbe/java8/samples/concurrent/Lockers.java new file mode 100644 index 00000000..52d5ae2d --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lockers.java @@ -0,0 +1,185 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * Lockers + * 在多线程编程里面一个重要的概念是锁定,如果一个资源是多个线程共享的,为了保证数据的完整性, + * 在进行事务性操作时需要将共享资源锁定,这样可以保证在做事务性操作时只有一个线程能对资源进行操作, + * 从而保证数据的完整性。在5.0以前,锁定的功能是由Synchronized关键字来实现的。 + */ +public class Lockers { + + /** + * 测试Lock的使用。在方法中使用Lock,可以避免使用Synchronized关键字。 + */ + public static class LockTest { + + Lock lock = new ReentrantLock();// 锁 + double value = 0d; // 值 + int addtimes = 0; + + /** + * 增加value的值,该方法的操作分为2步,而且相互依赖,必须实现在一个事务中 + * 所以该方法必须同步,以前的做法是在方法声明中使用Synchronized关键字。 + */ + public void addValue(double v) { + lock.lock();// 取得锁 + System.out.println("LockTest to addValue: " + v + " " + + System.currentTimeMillis()); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + this.value += v; + this.addtimes++; + lock.unlock();// 释放锁 + } + + public double getValue() { + return this.value; + } + } + + public static void testLockTest() throws Exception { + final LockTest lockTest = new LockTest(); + // 新建任务1,调用lockTest的addValue方法 + Runnable task1 = new Runnable() { + public void run() { + lockTest.addValue(55.55); + } + }; + // 新建任务2,调用lockTest的getValue方法 + Runnable task2 = new Runnable() { + public void run() { + System.out.println("value: " + lockTest.getValue()); + } + }; + // 新建任务执行服务 + ExecutorService cachedService = Executors.newCachedThreadPool(); + Future future = null; + // 同时执行任务1三次,由于addValue方法使用了锁机制,所以,实质上会顺序执行 + for (int i = 0; i < 3; i++) { + future = cachedService.submit(task1); + } + // 等待最后一个任务1被执行完 + future.get(); + // 再执行任务2,输出结果 + future = cachedService.submit(task2); + // 等待任务2执行完后,关闭任务执行服务 + future.get(); + cachedService.shutdownNow(); + } + + /** + * ReadWriteLock内置两个Lock,一个是读的Lock,一个是写的Lock。 + * 多个线程可同时得到读的Lock,但只有一个线程能得到写的Lock, + * 而且写的Lock被锁定后,任何线程都不能得到Lock。ReadWriteLock提供的方法有: + * readLock(): 返回一个读的lock + * writeLock(): 返回一个写的lock, 此lock是排他的。 + * ReadWriteLockTest很适合处理类似文件的读写操作。 + * 读的时候可以同时读,但不能写;写的时候既不能同时写也不能读。 + */ + public static class ReadWriteLockTest { + // 锁 + ReadWriteLock lock = new ReentrantReadWriteLock(); + // 值 + double value = 0d; + int addtimes = 0; + + /** + * 增加value的值,不允许多个线程同时进入该方法 + */ + public void addValue(double v) { + // 得到writeLock并锁定 + Lock writeLock = lock.writeLock(); + writeLock.lock(); + System.out.println("ReadWriteLockTest to addValue: " + v + " " + + System.currentTimeMillis()); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + try { + // 做写的工作 + this.value += v; + this.addtimes++; + } finally { + // 释放writeLock锁 + writeLock.unlock(); + } + } + + /** + * 获得信息。当有线程在调用addValue方法时,getInfo得到的信息可能是不正确的。 + * 所以,也必须保证该方法在被调用时,没有方法在调用addValue方法。 + */ + public String getInfo() { + // 得到readLock并锁定 + Lock readLock = lock.readLock(); + readLock.lock(); + System.out.println("ReadWriteLockTest to getInfo " + + System.currentTimeMillis()); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + try { + // 做读的工作 + return this.value + " : " + this.addtimes; + } finally { + // 释放readLock + readLock.unlock(); + } + } + } + + public static void testReadWriteLockTest() throws Exception { + final ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest(); + // 新建任务1,调用lockTest的addValue方法 + Runnable task_1 = new Runnable() { + public void run() { + readWriteLockTest.addValue(55.55); + } + }; + // 新建任务2,调用lockTest的getValue方法 + Runnable task_2 = new Runnable() { + public void run() { + System.out.println("info: " + readWriteLockTest.getInfo()); + } + }; + // 新建任务执行服务 + ExecutorService cachedService_1 = Executors.newCachedThreadPool(); + Future future_1 = null; + // 同时执行5个任务,其中前2个任务是task_1,后两个任务是task_2 + for (int i = 0; i < 2; i++) { + future_1 = cachedService_1.submit(task_1); + } + for (int i = 0; i < 2; i++) { + future_1 = cachedService_1.submit(task_2); + } + // 最后一个任务是task_1 + future_1 = cachedService_1.submit(task_1); + // 这5个任务的执行顺序应该是: + // 第一个task_1先执行,第二个task_1再执行;这是因为不能同时写,所以必须等。 + // 然后2个task_2同时执行;这是因为在写的时候,就不能读,所以都等待写结束, + // 又因为可以同时读,所以它们同时执行 + // 最后一个task_1再执行。这是因为在读的时候,也不能写,所以必须等待读结束后,才能写。 + + // 等待最后一个task_2被执行完 + future_1.get(); + cachedService_1.shutdownNow(); + } + + public static void main(String[] args) throws Exception { + Lockers.testLockTest(); + System.out.println("---------------------"); + Lockers.testReadWriteLockTest(); + } +} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/concurrent/SellTickets.java b/src/com/winterbe/java8/samples/concurrent/SellTickets.java new file mode 100644 index 00000000..3b1eb096 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/SellTickets.java @@ -0,0 +1,26 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.atomic.AtomicInteger; + +public class SellTickets { + AtomicInteger tickets = new AtomicInteger(100); + + class Seller implements Runnable { + @Override + public void run() { + while (tickets.get() > 0) { + int tmp = tickets.get(); + if (tickets.compareAndSet(tmp, tmp - 1)) { + System.out.println(Thread.currentThread().getName() + " " + tmp); + } + } + } + + } + + public static void main(String[] args) { + SellTickets st = new SellTickets(); + new Thread(st.new Seller(), "SellerA").start(); + new Thread(st.new Seller(), "SellerB").start(); + } +} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/concurrent/SemaphoreThreadDemo.java b/src/com/winterbe/java8/samples/concurrent/SemaphoreThreadDemo.java new file mode 100644 index 00000000..ff556f2f --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/SemaphoreThreadDemo.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019, SDCNCSI. All rights reserved. + */ + +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.Semaphore; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + */ +public class SemaphoreThreadDemo { + public static Semaphore semaphore = new Semaphore(5); + + static class ThreadDemo extends Thread { + @Override + public void run() { + try { + semaphore.acquire(); + System.out.println(Thread.currentThread().getId() + "号线程在"+System.currentTimeMillis()+"获取资源"); + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + }finally { + semaphore.release(); + } + } + } + + public static void main(String[] args) throws InterruptedException { + for (int i = 0; i < 30; i++) { + new ThreadDemo().start(); + } + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Test.java b/src/com/winterbe/java8/samples/concurrent/Test.java new file mode 100644 index 00000000..a6ea0397 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Test.java @@ -0,0 +1,61 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.*; +import java.util.Date; +import java.util.List; +import java.util.ArrayList; + +/** + * 有返回值的线程 + */ +@SuppressWarnings("unchecked") +public class Test { + public static void main(String[] args) throws ExecutionException, + InterruptedException { + System.out.println("----程序开始运行----"); + Date date1 = new Date(); + + int taskSize = 5; + // 创建一个线程池 + ExecutorService pool = Executors.newFixedThreadPool(taskSize); + // 创建多个有返回值的任务 + List list = new ArrayList(); + for (int i = 0; i < taskSize; i++) { + Callable c = new MyCallable(i + " "); + // 执行任务并获取Future对象 + Future f = pool.submit(c); + // System.out.println(">>>" + f.get().toString()); + list.add(f); + } + // 关闭线程池 + pool.shutdown(); + + // 获取所有并发任务的运行结果 + for (Future f : list) { + // 从Future对象上获取任务的返回值,并输出到控制台 + System.out.println(">>>" + f.get().toString()); + } + + Date date2 = new Date(); + System.out.println("----程序结束运行----,程序运行时间【" + + (date2.getTime() - date1.getTime()) + "毫秒】"); + } +} + +class MyCallable implements Callable { + private String taskNum; + + MyCallable(String taskNum) { + this.taskNum = taskNum; + } + + public Object call() throws Exception { + System.out.println(">>>" + taskNum + "任务启动"); + Date dateTmp1 = new Date(); + Thread.sleep(1000); + Date dateTmp2 = new Date(); + long time = dateTmp2.getTime() - dateTmp1.getTime(); + System.out.println(">>>" + taskNum + "任务终止"); + return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】"; + } +} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/lambda/Lambda1.java b/src/com/winterbe/java8/samples/lambda/Lambda1.java index 5bb5b658..54b37abd 100644 --- a/src/com/winterbe/java8/samples/lambda/Lambda1.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda1.java @@ -38,11 +38,13 @@ public int compare(String a, String b) { List names2 = Arrays.asList("peter", null, "anna", "mike", "xenia"); names2.sort(Comparator.nullsLast(String::compareTo)); System.out.println(names2); + names2.forEach(System.out ::println); List names3 = null; Optional.ofNullable(names3).ifPresent(list -> list.sort(Comparator.naturalOrder())); - + System.out.println(); + System.out.println(); System.out.println(names3); } diff --git a/src/com/winterbe/java8/samples/lambda/Lambda6.java b/src/com/winterbe/java8/samples/lambda/Lambda6.java new file mode 100644 index 00000000..f0db5ae7 --- /dev/null +++ b/src/com/winterbe/java8/samples/lambda/Lambda6.java @@ -0,0 +1,12 @@ +package com.winterbe.java8.samples.lambda; + +import java.util.stream.Stream; + +/** + * Created by 王太成 on 2016/9/22. + */ +public class Lambda6 { + public static void main(String[] args) { + Stream.iterate(1, item -> item + 1).limit(10).forEach(System.out::println); + } +} diff --git a/src/com/winterbe/java8/samples/lambda/Lambda7.java b/src/com/winterbe/java8/samples/lambda/Lambda7.java new file mode 100644 index 00000000..4df2c603 --- /dev/null +++ b/src/com/winterbe/java8/samples/lambda/Lambda7.java @@ -0,0 +1,94 @@ +package com.winterbe.java8.samples.lambda; + +import java.util.Arrays; +import java.util.IntSummaryStatistics; +import java.util.List; +import java.util.function.Predicate; + +/** + * 类名 :Lambda7 + * 项目名称 :java8-tutorial + * 创建时间 :2016/12/30 + * 作 者:sd-wangtaicheng@sdcncsi.com.cn + * 版 本:v1 + */ +public class Lambda7 { + + public static void main(String[] args) { + threadTest(); + listTest(); + } + + private static void threadTest() { + //Before Java 8: + new Thread(new Runnable() { + @Override + public void run() { + System.out.println("Before Java8 "); + } + }).start(); + //Java 8 way: + new Thread(() -> System.out.println("In Java8!")).start(); + } + + private static void listTest() { + List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); + + System.out.println("Languages which starts with J :"); + filter(languages, (str) -> str.startsWith("J")); + + System.out.println("Languages which ends with a "); + filter(languages, (str) -> str.endsWith("a")); + + System.out.println("Print all languages :"); + filter(languages, (str) -> true); + + System.out.println("Print no language : "); + filter(languages, (str) -> false); + + System.out.println("Print language whose length greater than 4:"); + filter(languages, (str) -> str.length() > 4); + + Predicate startsWithJ = (n) -> n.startsWith("J"); + Predicate fourLetterLong = (n) -> n.length() == 4; + + languages.stream() + .filter(startsWithJ.and(fourLetterLong)) + .forEach((n) -> System.out.println("\nName, which starts with 'J' and four letter long is : " + n)); + System.out.println(); + List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); + costBeforeTax.stream().map((cost) -> cost + .12 * cost) + .forEach(System.out::println); + + double total = 0; + for (Integer cost : costBeforeTax) { + double price = cost + .12 * cost; + total = total + price; + + } + System.out.println("Total : " + total); + + double bill = costBeforeTax.stream().map((cost) -> cost + .12 * cost) + .reduce((sum, cost) -> sum + cost) + .get(); + System.out.println("Total : " + bill); + //Get count, min, max, sum, and average for numbers + List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); + IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x) + .summaryStatistics(); + System.out.println("Highest prime number in List : " + stats.getMax()); + System.out.println("Lowest prime number in List : " + stats.getMin()); + System.out.println("Sum of all prime numbers : " + stats.getSum()); + System.out.println("Average of all prime numbers : " + stats.getAverage()); + + + } + + //Even better + public static void filter(List names, Predicate condition) { + names.stream().filter((name) -> (condition.test(name))) + .forEach((name) -> { + System.out.println(name + " "); + }); + } +} diff --git a/src/com/winterbe/java8/samples/stream/Streams14.java b/src/com/winterbe/java8/samples/stream/Streams14.java new file mode 100644 index 00000000..c917fcc6 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams14.java @@ -0,0 +1,16 @@ +package com.winterbe.java8.samples.stream; + +import java.util.stream.IntStream; + +/** + * 描述 + * + * @author 王太成 + * @version 1.0.1 + * @since 2015/11/23 + */ +public class Streams14 { + public static void main(String[] args) { + IntStream.range(1,10).forEach(i->System.out.println(i)); + } +} diff --git a/src/com/winterbe/java8/samples/time/LocalDateMain.java b/src/com/winterbe/java8/samples/time/LocalDateMain.java new file mode 100644 index 00000000..3c0496c7 --- /dev/null +++ b/src/com/winterbe/java8/samples/time/LocalDateMain.java @@ -0,0 +1,44 @@ +package com.winterbe.java8.samples.time; + +import java.time.LocalDate; +import java.time.MonthDay; +import java.time.temporal.TemporalAdjusters; + +import static java.lang.String.format; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + * @since 2019/1/22 + */ +public class LocalDateMain { + + public static void main(String[] args) { + //today + LocalDate today = LocalDate.now(); + System.out.println(format("today is %s",today)); + //本月第一天 + LocalDate firstDay = today.with(TemporalAdjusters.firstDayOfMonth()); + System.out.println(firstDay); + LocalDate firstDay2 = today.withDayOfMonth(1); + System.out.println(firstDay2); + //本月最后一天 + LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfMonth()); + System.out.println(lastDay); + //当前日期+1天 + LocalDate tomorrow = today.plusDays(1); + System.out.println(tomorrow); + //判断是否为闰年 + boolean isLeapYear = tomorrow.isLeapYear(); + System.out.println(format("闰年: %s",isLeapYear)); + + LocalDate birthday = LocalDate.of(1990, 10, 12); + MonthDay birthdayMd = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth()); + MonthDay today1 = MonthDay.from(LocalDate.of(2016, 10, 12)); + System.out.println(today1.equals(birthdayMd)); + + //日期比较 + LocalDate specifyDate = LocalDate.of(2015, 10, 20); + System.out.println(today.isAfter(specifyDate)); + } + +} diff --git a/src/com/winterbe/java8/samples/time/LocalDateTimeMain.java b/src/com/winterbe/java8/samples/time/LocalDateTimeMain.java new file mode 100644 index 00000000..3f5d02a6 --- /dev/null +++ b/src/com/winterbe/java8/samples/time/LocalDateTimeMain.java @@ -0,0 +1,28 @@ +package com.winterbe.java8.samples.time; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + * @since 2019/1/22 + */ +public class LocalDateTimeMain { + public static void main(String[] args) { + //查看当前的时区 + ZoneId defaultZone = ZoneId.systemDefault(); + System.out.println(defaultZone); + + //查看美国纽约当前的时间 + ZoneId america = ZoneId.of("America/New_York"); + LocalDateTime shanghaiTime = LocalDateTime.now(); + LocalDateTime americaDateTime = LocalDateTime.now(america); + System.out.println(shanghaiTime); + System.out.println(americaDateTime); + + //带有时区的时间 + ZonedDateTime americaZoneDateTime = ZonedDateTime.now(america); + System.out.println(americaZoneDateTime); + } +} diff --git a/src/com/winterbe/java8/samples/time/LocalTimeMain.java b/src/com/winterbe/java8/samples/time/LocalTimeMain.java new file mode 100644 index 00000000..76f0cb08 --- /dev/null +++ b/src/com/winterbe/java8/samples/time/LocalTimeMain.java @@ -0,0 +1,30 @@ +package com.winterbe.java8.samples.time; + +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; + +/** + * @author sd-wangtaicheng@sdcncsi.com.cn + * @since 2019/1/22 + */ +public class LocalTimeMain { + public static void main(String[] args) { + //获取当前的时间 + LocalTime nowTime = LocalTime.now(); + System.out.println(nowTime); + //如果不想显示毫秒 + LocalTime nowTime2 = LocalTime.now().withNano(0); + System.out.println(nowTime2); + //指定时间 + LocalTime time = LocalTime.of(14, 10, 21); + LocalTime time2 = LocalTime.parse("12:00:01"); + System.out.println(time); + System.out.println(time2); + //当前时间增加2小时 + LocalTime nowTimePlus2Hour = nowTime.plusHours(2); + System.out.println(nowTimePlus2Hour); + //或者 + LocalTime nowTimePlus2Hour2 = nowTime.plus(2, ChronoUnit.HOURS); + System.out.println(nowTimePlus2Hour2); + } +} diff --git a/src/com/winterbe/java8/samples/time/readme.md b/src/com/winterbe/java8/samples/time/readme.md new file mode 100644 index 00000000..c4a296f5 --- /dev/null +++ b/src/com/winterbe/java8/samples/time/readme.md @@ -0,0 +1,195 @@ + +### 在java8中,java.time包下主要包含下面几个主要的类 +``` +Instant:时间戳 +Duration:持续时间,时间差 +LocalDate:只包含日期,比如:2016-10-20 +LocalTime:只包含时间,比如:23:12:10 +LocalDateTime:包含日期和时间,比如:2016-10-20 23:14:21 +Period:时间段 +ZoneOffset:时区偏移量,比如:+8:00 +ZonedDateTime:带时区的时间 +Clock:时钟,比如获取目前美国纽约的时间 +``` +### java.time.format包中的 +``` +DateTimeFormatter:时间格式化 +``` + +#### 1、获取今天的日期 + +```java +LocalDate todayDate = LocalDate.now(); +System.out.println("今天的日期:"+todayDate); +//结果 +今天的日期:2016-10-20 +``` + +#### 2、指定日期,进行相应操作 + +```java +//取2016年10月的第1天 +LocalDate firstDay = oneday.with(TemporalAdjusters.firstDayOfMonth()); +System.out.println(firstDay); + +//取2016年10月的第1天,另外一种写法 +LocalDate firstDay2 = oneday.withDayOfMonth(1); +System.out.println(firstDay2); + +//取2016年10月的最后1天,不用考虑大月,小月,平年,闰年 +LocalDate lastDay = oneday.with(TemporalAdjusters.lastDayOfMonth()); +System.out.println(lastDay); + +//当前日期+1天 +LocalDate tomorrow = oneday.plusDays(1); +System.out.println(tomorrow); + +//判断是否为闰年 +boolean isLeapYear = tomorrow.isLeapYear(); +System.out.println(isLeapYear); + +//运行结果 +2016-10-20 +2016-10-01 +2016-10-01 +2016-10-31 +2016-10-21 +true +``` + +#### 3、生日检查或者账单日检查 + +开发过程中,经常需要为过生日的用户送上一些祝福,例如,用户的生日为1990-10-12,如果今天是2016-10-12,那么今天就是用户的生日(按公历/身份证日期来算),那么通过java8新的日期库,我们该如何来进行判断? + +在java8中,可以使用`MonthDay`,该类不包含年份信息,当然还有一个类是`YearMonth` + +```java +LocalDate birthday = LocalDate.of(1990, 10, 12); +MonthDay birthdayMd = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth()); +MonthDay today = MonthDay.from(LocalDate.of(2016, 10, 12)); +System.out.println(today.equals(birthdayMd)); +//结果 +true +``` + +#### 4、获取当前的时间 + +日期主要是使用LocalTime,该类不包含日期,只有时间信息 + +```java +//获取当前的时间 +LocalTime nowTime = LocalTime.now(); //结果14:29:40.558 + +//如果不想显示毫秒 +LocalTime nowTime2 = LocalTime.now().withNano(0); //14:43:14 + +//指定时间 +LocalTime time = LocalTime.of(14, 10, 21); //14:10:21 +LocalTime time2 = LocalTime.parse("12:00:01"); // 12:00:01 + +//当前时间增加2小时 +LocalTime nowTimePlus2Hour = nowTime.plusHours(2); //16:47:23.144 +//或者 +LocalTime nowTimePlus2Hour2 = nowTime.plus(2, ChronoUnit.HOURS); +``` + +#### 5、日期前后比较 + +比较2个日期哪个在前,哪个在后,java8 LocalDate提供了2个方法,`isAfter()`,`isBefore` + +```java +LocalDate today = LocalDate.now(); +LocalDate specifyDate = LocalDate.of(2015, 10, 20); +System.out.println(today.isAfter(specifyDate)); //true +``` + +#### 6、处理不同时区的时间 + +java8中,将日期,时间,时区都很好的进行了分离。 + +```java +//查看当前的时区 +ZoneId defaultZone = ZoneId.systemDefault(); +System.out.println(defaultZone); //Asia/Shanghai + +//查看美国纽约当前的时间 +ZoneId america = ZoneId.of("America/New_York"); +LocalDateTime shanghaiTime = LocalDateTime.now(); +LocalDateTime americaDateTime = LocalDateTime.now(america); +System.out.println(shanghaiTime); //2016-11-06T15:20:27.996 +System.out.println(americaDateTime); //2016-11-06T02:20:27.996 ,可以看到美国与北京时间差了13小时 + +//带有时区的时间 +ZonedDateTime americaZoneDateTime = ZonedDateTime.now(america); +System.out.println(americaZoneDateTime); //2016-11-06T02:23:44.863-05:00[America/New_York] +``` + +#### 7、比较两个日期之前时间差 + +在项目中,经常需要比较两个日期之间相差几天,或者相隔几个月,我们可以使用java8的Period来进行处理。 + +```java +LocalDate today = LocalDate.now(); +LocalDate specifyDate = LocalDate.of(2015, 10, 2); +Period period = Period.between(specifyDate, today); + +System.out.println(period.getDays()); //4 +System.out.println(period.getMonths()); //1 +System.out.println(specifyDate.until(today, ChronoUnit.DAYS)); //401 +//输出结果 +4 +1 +401 +``` + +我们可以看到,我们使用Period类比较天数,比较奇怪,他返回的值,并不是2个日期之间总共的天数差,而是一个相对天数差,比如,5月1日,和10月2日,他比较的是仅仅2个天之间的差,那1号和2号,相差1天,而实际上,因为中间相差了好几个月,所以真正的天数差肯定不是1天,所以我们可以使用until,并指明精度单位是days,就可以计算真正的天数差了。 + +#### 8、日期时间格式解析、格式化 + +在java8之前,我们进行时间格式化主要是使用`SimpleDateFormat`,而在java8中,主要是使用`DateTimeFormatter`,java8中,预定义了一些标准的时间格式,我们可以直接将时间转换为标准的时间格式: + +```java +String specifyDate = "20151011"; +DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE; +LocalDate formatted = LocalDate.parse(specifyDate,formatter); +System.out.println(formatted); +//输出 +2015-10-11 +``` + +当然,很多时间标准的时间格式可能也不满足我们的要求,我们需要转为自定义的时间格式 + +```java +DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("YYYY MM dd"); +System.out.println(formatter2.format(LocalDate.now())); +//结果 +2015 10 11 +``` + +#### 9、java8 时间类与Date类的相互转化 + +在转换中,我们需要注意,因为java8之前Date是包含日期和时间的,而LocalDate只包含日期,LocalTime只包含时间,所以与Date在互转中,势必会丢失日期或者时间,或者会使用起始时间。如果转LocalDateTime,那么就不存在信息误差。 + +```java +//Date与Instant的相互转化 +Instant instant = Instant.now(); +Date date = Date.from(instant); +Instant instant2 = date.toInstant(); + +//Date转为LocalDateTime +Date date2 = new Date(); +LocalDateTime localDateTime2 = LocalDateTime.ofInstant(date2.toInstant(), ZoneId.systemDefault()); + +//LocalDateTime转Date +LocalDateTime localDateTime3 = LocalDateTime.now(); +Instant instant3 = localDateTime3.atZone(ZoneId.systemDefault()).toInstant(); +Date date3 = Date.from(instant); + +//LocalDate转Date +//因为LocalDate不包含时间,所以转Date时,会默认转为当天的起始时间,00:00:00 +LocalDate localDate4 = LocalDate.now(); +Instant instant4 = localDate4.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(); +Date date4 = Date.from(instant); +``` + +总结,其实想说的这,这篇文章是一篇难产很久的文章,自从十一假期后,一直找不到写代码的感觉,所以这篇文章拖了1个月。 \ No newline at end of file diff --git a/src/com/winterbe/java8/study/lambda/Lesson3.java b/src/com/winterbe/java8/study/lambda/Lesson3.java new file mode 100644 index 00000000..2e05ff3e --- /dev/null +++ b/src/com/winterbe/java8/study/lambda/Lesson3.java @@ -0,0 +1,29 @@ +package com.winterbe.java8.study.lambda; + +/** + * 类名 :Lesson3 + * 项目名称 :java8-tutorial + * 创建时间 :2017/6/16 + * 作 者:sd-wangtaicheng@sdcncsi.com.cn + * 版 本:v1 + */ +public class Lesson3 { + + public static void main(String[] args) { + Runnable r1 = ()-> System.out.println("r1"); + Runnable r2 = new Runnable() { + @Override + public void run() { + System.out.println("r2"); + } + }; + + process(r1); + process(r2); + process(()-> System.out.println("r3")); + + } + public static void process(Runnable r){ + r.run(); + } +} diff --git a/src/com/winterbe/thread/TestFutureCache.java b/src/com/winterbe/thread/TestFutureCache.java new file mode 100644 index 00000000..dd5539b3 --- /dev/null +++ b/src/com/winterbe/thread/TestFutureCache.java @@ -0,0 +1,95 @@ +package com.winterbe.thread; + +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; + +public class TestFutureCache { + private final ConcurrentHashMap> cacheMap = new ConcurrentHashMap>(); + + public Object getCache(K keyValue, String ThreadName) { + Future value = null; + try { + System.out.println("ThreadName getCache==============" + ThreadName); + //从缓存获取数据 + value = cacheMap.get(keyValue); + //如果没有的话,把数据放到缓存 + if (value == null) { + value = putCache(keyValue, ThreadName); + return value.get(); + } + return value.get(); + + } catch (Exception e) { + } + return null; + } + + + public Future putCache(K keyValue, final String ThreadName) { +// //把数据放到缓存 + Future value = null; + Callable callable = new Callable() { + @SuppressWarnings("unchecked") + @Override + public V call() throws Exception { + //可以根据业务从数据库获取等取得数据,这边就模拟已经获取数据了 + System.out.println("ThreadName 执行业务数据并返回处理结果的数据(访问数据库等)==============" + ThreadName); + return (V) "dataValue"; + } + }; + FutureTask futureTask = new FutureTask(callable); + value = cacheMap.putIfAbsent(keyValue, futureTask); + if (value == null) { + value = futureTask; + futureTask.run(); + } + return value; + } + + + public static void main(String[] args) { + final TestFutureCache testGuaVA = new TestFutureCache(); + + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + + System.out.println("T1======start========"); + Object value = testGuaVA.getCache("key", "T1"); + System.out.println("T1 value==============" + value); + System.out.println("T1======end========"); + + } + }); + + Thread t2 = new Thread(new Runnable() { + @Override + public void run() { + System.out.println("T2======start========"); + Object value = testGuaVA.getCache("key", "T2"); + System.out.println("T2 value==============" + value); + System.out.println("T2======end========"); + + } + }); + + Thread t3 = new Thread(new Runnable() { + @Override + public void run() { + System.out.println("T3======start========"); + Object value = testGuaVA.getCache("key", "T3"); + System.out.println("T3 value==============" + value); + System.out.println("T3======end========"); + + } + }); + + t1.start(); + t2.start(); + t3.start(); + + } + +} \ No newline at end of file diff --git a/src/com/winterbe/thread/TestGuaVA.java b/src/com/winterbe/thread/TestGuaVA.java new file mode 100644 index 00000000..0c3e6e6b --- /dev/null +++ b/src/com/winterbe/thread/TestGuaVA.java @@ -0,0 +1,78 @@ +package com.winterbe.thread; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +public class TestGuaVA { + private Cache cache = CacheBuilder.newBuilder().maximumSize(2).expireAfterWrite(10, TimeUnit.MINUTES).build(); + + public Object getCache(K keyValue, final String ThreadName) { + Object value = null; + try { + System.out.println("ThreadName getCache==============" + ThreadName); +//从缓存获取数据 + value = cache.get(keyValue, new Callable() { + @SuppressWarnings("unchecked") + public V call() { + System.out.println("ThreadName 执行业务数据并返回处理结果的数据(访问数据库等)==============" + ThreadName); + return (V) "dataValue"; + } + }); + } catch (ExecutionException e) { + e.printStackTrace(); + } + return value; + } + + + public static void main(String[] args) { + final TestGuaVA TestGuaVA = new TestGuaVA(); + + + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + + System.out.println("T1======start========"); + Object value = TestGuaVA.getCache("key", "T1"); + System.out.println("T1 value==============" + value); + System.out.println("T1======end========"); + + } + }); + + Thread t2 = new Thread(new Runnable() { + @Override + public void run() { + System.out.println("T2======start========"); + Object value = TestGuaVA.getCache("key", "T2"); + System.out.println("T2 value==============" + value); + System.out.println("T2======end========"); + + } + }); + + Thread t3 = new Thread(new Runnable() { + @Override + public void run() { + System.out.println("T3======start========"); + Object value = TestGuaVA.getCache("key", "T3"); + System.out.println("T3 value==============" + value); + System.out.println("T3======end========"); + + } + }); + + t1.start(); + t2.start(); + t3.start(); + + + } + + +} \ No newline at end of file