阅读文本大概需要15分钟。

1、线程状态转换

无限期等待:

限期等待:

线程生命流程:

2、实现方式

代码实现样例【三种方式】:

  1. package com.cnblogs.mufasa.demo2;

  2. import java.util.concurrent.Callable;

  3. public class test1_Runnable implements Runnable{

  4. @Override

  5. public void run() {

  6. for(int i=0;i<50;i++){

  7. System.out.println("当前线程:"+i);

  8. }

  9. }

  10. }

  11. class test2_Callable implements Callable<String> {

  12. private int num;

  13. public test2_Callable(){}

  14. public test2_Callable(int num){

  15. this.num=num;

  16. }

  17. @Override

  18. public String call() throws Exception {

  19. for(int i=0;i<50;i++){

  20. System.out.println(this.num+"线程:"+i);

  21. }

  22. return num+"线程已完成";

  23. }

  24. }

  25. class test3_Thread extends Thread {

  26. private int num;

  27. public test3_Thread(){}

  28. public test3_Thread(int num){

  29. this.num=num;

  30. }

  31. @Override

  32. public void run() {

  33. for(int i=0;i<50;i++){

  34. System.out.println(this.num+"线程:"+i);

  35. }

  36. }

  37. }

  1. package com.cnblogs.mufasa.demo2;

  2. import java.util.concurrent.ExecutionException;

  3. import java.util.concurrent.FutureTask;

  4. public class Client {

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

  6. //实现 Runnable 接口

  7. // test1_Runnable instance=new test1_Runnable();

  8. // Thread thread=new Thread(instance);

  9. // Thread thread1=new Thread(instance);

  10. // thread.start();

  11. // thread1.start();

  12. //实现 Callable 接口

  13. // test2_Callable instance=new test2_Callable(1);

  14. // FutureTask<String> ft=new FutureTask<>(instance);

  15. // Thread thread = new Thread(ft);

  16. // test2_Callable instance1=new test2_Callable(2);

  17. // FutureTask<String> ft2=new FutureTask<>(instance1);

  18. // Thread thread1 = new Thread(ft2);

  19. //

  20. // thread.start();

  21. // thread1.start();

  22. // System.out.println(ft.get());

  23. // System.out.println(ft2.get());

  24. //继承 Thread 类

  25. test3_Thread thread1=new test3_Thread(1);

  26. test3_Thread thread2=new test3_Thread(2);

  27. thread1.start();

  28. thread2.start();

  29. }

  30. }

3、基础线程机制

代码实现样例:

  1. package com.cnblogs.mufasa.demo3;

  2. public class Client1 {

  3. public static void main(String[] args) throws InterruptedException {

  4. //设置守护线程 setDaemon 伴随线程而运行

  5. // Thread thread1 = new Thread(new test1_Runnable(1));

  6. // Thread thread2 = new Thread(new test3_Thread(2));

  7. // thread1.setDaemon(true);

  8. // thread1.start();

  9. // thread2.start();

  10. //sleep Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec 单位为毫秒

  11. // sleep() 可能会抛出 InterruptedException,因为异常不能跨线程传播回 main() 中,因此必须在本地进行处理

  12. // Thread thread1 = new Thread(()->{

  13. // try {

  14. // System.out.println("延迟2s");

  15. // Thread.sleep(2000);

  16. // System.out.println("延迟结束");

  17. // } catch (InterruptedException e) {

  18. // e.printStackTrace();

  19. // }

  20. // });

  21. // thread1.start();

  22. // new Thread(new Runnable() {

  23. // @Override

  24. // public void run() {

  25. // System.out.println("延迟2s");

  26. // try {

  27. // Thread.sleep(2000);

  28. // System.out.println("延迟结束");

  29. // Thread.yield();//可以让出资源

  30. // Thread.sleep(2000);

  31. // } catch (InterruptedException e) {

  32. // e.printStackTrace();

  33. // }finally {

  34. // System.out.println("线程1运行结束");

  35. // }

  36. // }

  37. // }).start();

  38. //

  39. // new Thread(()->{

  40. // try {

  41. // Thread.sleep(2000);

  42. // } catch (InterruptedException e) {

  43. // e.printStackTrace();

  44. // }finally {

  45. // System.out.println("线程2延迟结束");

  46. // }

  47. // }).start();

  48. Thread t = new Thread(new Runnable(){

  49. public void run(){

  50. System.out.println("First task started");

  51. System.out.println("Sleeping for 2 seconds");

  52. try{

  53. Thread.sleep(2000);

  54. } catch (InterruptedException e){

  55. e.printStackTrace();

  56. }

  57. System.out.println("First task completed");

  58. }

  59. });

  60. Thread t1 = new Thread(new Runnable(){

  61. public void run(){

  62. System.out.println("Second task completed");

  63. }

  64. });

  65. //在t执行完毕后t1执行

  66. t.start(); // Line 15

  67. t.join(); // Line 16

  68. t1.start();

  69. }

  70. }

4、中断

  1. package com.cnblogs.mufasa.demo4;

  2. import java.util.concurrent.Executor;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. import java.util.concurrent.Future;

  6. import static java.lang.Thread.interrupted;

  7. class InterruptExample extends Thread {

  8. @Override

  9. public void run() {

  10. System.out.println("sleep 2s");

  11. try {

  12. Thread.sleep(2000);

  13. System.out.println("Thread run");

  14. } catch (InterruptedException e) {

  15. System.out.println("休眠中断");

  16. e.printStackTrace();

  17. }

  18. }

  19. }

  20. class InterruptExample1 extends Thread {

  21. @Override

  22. public void run() {

  23. while (!interrupted()) {

  24. // ..

  25. }

  26. System.out.println("Thread end");

  27. }

  28. }

  29. public class Client {

  30. public static void main(String[] args) {

  31. // InterruptExample thread1 = new InterruptExample();

  32. // thread1.start();

  33. // thread1.interrupt();

  34. // System.out.println("Main run");

  35. // InterruptExample1 thread2 = new InterruptExample1();

  36. // thread2.start();

  37. // thread2.interrupt();

  38. // ExecutorService executorService = Executors.newCachedThreadPool();

  39. // executorService.execute(() -> {

  40. // try {

  41. // Thread.sleep(2000);

  42. // System.out.println("Thread run");

  43. // } catch (InterruptedException e) {

  44. // System.out.println("线程程序池全体中断");

  45. // e.printStackTrace();

  46. // }

  47. // });

  48. // executorService.shutdownNow();

  49. // System.out.println("Main run");

  50. ExecutorService executorService = Executors.newCachedThreadPool();

  51. Future<?> future=executorService.submit(()->{

  52. System.out.println("3");

  53. while (!interrupted()){

  54. System.out.println("2");

  55. }

  56. System.out.println("1");

  57. });

  58. future.cancel(true);//强制中断

  59. }

  60. }

5、互斥同步

代码实现:

  1. package com.cnblogs.mufasa.demo5;

  2. import java.util.concurrent.Executor;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. import java.util.concurrent.locks.Lock;

  6. import java.util.concurrent.locks.ReentrantLock;

  7. class SynchronizedExample {//同步代码块,作用于同一个对象

  8. public void func1() {

  9. synchronized (this) {

  10. for (int i = 0; i < 10; i++) {

  11. System.out.print(i + " ");

  12. }

  13. }

  14. }

  15. }

  16. class SynchronizedExample1 {//同步方法,作用于同一个对象

  17. public synchronized void func1() {

  18. for (int i = 0; i < 10; i++) {

  19. System.out.print(i + " ");

  20. }

  21. }

  22. }

  23. class SynchronizedExample2 {//同步类,作用于整个类。

  24. public void func1() {

  25. synchronized(SynchronizedExample2.class){

  26. for (int i = 0; i < 10; i++) {

  27. System.out.print(i + " ");

  28. }

  29. }

  30. }

  31. }

  32. class SynchronizedExample3 {//同步静态方法,作用于整个类。

  33. public static synchronized void func1() {

  34. for (int i = 0; i < 10; i++) {

  35. System.out.print(i + " ");

  36. }

  37. }

  38. }

  39. class LockExample {//ReentrantLock 是 java.util.concurrent(J.U.C)包中的锁。

  40. private Lock lock=new ReentrantLock();

  41. public void func() {

  42. lock.lock();

  43. try {

  44. for (int i = 0; i < 10; i++) {

  45. System.out.print(i + " ");

  46. }

  47. }finally {

  48. lock.unlock();//确保解锁,防止死锁

  49. }

  50. }

  51. }

  52. public class Client {

  53. public static void main(String[] args) {

  54. //synchronized-代码块 相同对象-同步代码块

  55. // SynchronizedExample e1=new SynchronizedExample();

  56. // ExecutorService executorService= Executors.newCachedThreadPool();

  57. // executorService.execute(()->e1.func1());

  58. // executorService.execute(()->e1.func1());

  59. //synchronized-代码块 不同对象-同步代码块,没有同步!!!

  60. // SynchronizedExample e1 = new SynchronizedExample();

  61. // SynchronizedExample e2 = new SynchronizedExample();

  62. // ExecutorService executorService = Executors.newCachedThreadPool();

  63. // executorService.execute(()->e1.func1());

  64. // executorService.execute(()->e2.func1());

  65. //synchronized-方法 不同对象,没有同步!!!

  66. // SynchronizedExample1 e1 = new SynchronizedExample1();

  67. // SynchronizedExample1 e2 = new SynchronizedExample1();

  68. // ExecutorService executorService = Executors.newCachedThreadPool();

  69. // executorService.execute(()->e1.func1());

  70. // executorService.execute(()->e2.func1());

  71. //synchronized-类 不同对象,有同步

  72. // SynchronizedExample2 e1 = new SynchronizedExample2();

  73. // SynchronizedExample2 e2 = new SynchronizedExample2();

  74. // ExecutorService executorService = Executors.newCachedThreadPool();

  75. // executorService.execute(()->e1.func1());

  76. // executorService.execute(()->e2.func1());

  77. //synchronized-静态方法 不同对象,有同步

  78. // SynchronizedExample3 e1 = new SynchronizedExample3();

  79. // SynchronizedExample3 e2 = new SynchronizedExample3();

  80. // ExecutorService executorService = Executors.newCachedThreadPool();

  81. // executorService.execute(()->e1.func1());

  82. // executorService.execute(()->e2.func1());

  83. //JDK实现的锁,作用一个对象

  84. LockExample lockExample = new LockExample();

  85. LockExample lockExample1 = new LockExample();

  86. ExecutorService executorService = Executors.newCachedThreadPool();

  87. executorService.execute(() -> lockExample.func());

  88. // executorService.execute(() -> lockExample1.func());

  89. executorService.execute(() -> lockExample.func());

  90. }

  91. }

6、线程协作

样例代码:

  1. package com.cnblogs.mufasa.demo6;

  2. import java.util.concurrent.Executor;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. import java.util.concurrent.locks.Condition;

  6. import java.util.concurrent.locks.Lock;

  7. import java.util.concurrent.locks.ReentrantLock;

  8. class JoinExample{

  9. private class A extends Thread{

  10. @Override

  11. public void run(){

  12. for(int i=0;i<10;i++){

  13. System.out.println("A:"+i);

  14. }

  15. }

  16. }

  17. private class B extends Thread {

  18. private A a;

  19. B(A a) {

  20. this.a = a;

  21. }

  22. @Override

  23. public void run() {

  24. try {

  25. a.join();//先完成A线程,继续B线程

  26. } catch (InterruptedException e) {

  27. e.printStackTrace();

  28. }

  29. System.out.println("B");

  30. }

  31. }

  32. public void test() {

  33. A a = new A();

  34. B b = new B(a);

  35. b.start();

  36. a.start();

  37. }

  38. }

  39. class WaitNotifyExample{

  40. public synchronized void before(){

  41. System.out.println("before");

  42. notifyAll();//通知等待的线程

  43. }

  44. public synchronized void after(){

  45. try {

  46. wait();//先进行等待

  47. } catch (InterruptedException e) {

  48. e.printStackTrace();

  49. }

  50. for(int i=0;i<10;i++){

  51. System.out.print(i);

  52. }

  53. System.out.println("after");

  54. }

  55. }

  56. class AwaitSingalExample{

  57. private Lock lock=new ReentrantLock();

  58. private Condition condition=lock.newCondition();

  59. public void before(){

  60. lock.lock();

  61. try {

  62. System.out.println("before");

  63. condition.signalAll();

  64. }finally {

  65. lock.unlock();

  66. }

  67. }

  68. public void after(){

  69. lock.lock();

  70. try {

  71. condition.await();

  72. System.out.println("after");

  73. } catch (InterruptedException e) {

  74. e.printStackTrace();

  75. }finally {

  76. lock.unlock();

  77. }

  78. }

  79. }

  80. public class Client {

  81. public static void main(String[] args) {

  82. // JoinExample example=new JoinExample();

  83. // example.test();

  84. // ExecutorService executorService = Executors.newCachedThreadPool();

  85. // WaitNotifyExample example = new WaitNotifyExample();

  86. // WaitNotifyExample example1 = new WaitNotifyExample();

  87. // executorService.execute(() -> example.after());

  88. // executorService.execute(() -> example1.after());

  89. // executorService.execute(() -> example.before());

  90. // executorService.execute(() -> example1.before());

  91. ExecutorService executorService= Executors.newCachedThreadPool();

  92. AwaitSingalExample example=new AwaitSingalExample();

  93. executorService.execute(()->example.after());

  94. executorService.execute(()->example.before());

  95. }

  96. }

7、J.U.C-AQS【java.util.concurrent】

样例代码:

  1. package com.cnblogs.mufasa.demo7;

  2. import java.util.concurrent.*;

  3. class CyclicBarrier {

  4. private int parties;

  5. private int count;

  6. private Runnable barrierCommand;

  7. public CyclicBarrier(int parties,Runnable barrierAction){

  8. if (parties <= 0) throw new IllegalArgumentException();

  9. this.parties = parties;

  10. this.count = parties;

  11. this.barrierCommand = barrierAction;

  12. }

  13. public CyclicBarrier(int parties) {

  14. this(parties, null);

  15. }

  16. }

  17. public class Client {

  18. public static void main(String[] args) throws InterruptedException {

  19. final int clientCount=5;

  20. final int totalRequestCount=10;

  21. Semaphore semaphore=new Semaphore(clientCount);

  22. ExecutorService executorService=Executors.newCachedThreadPool();

  23. for(int i=0;i<totalRequestCount;i++){

  24. executorService.execute(()->{

  25. try {

  26. semaphore.acquire();

  27. System.out.print(semaphore.availablePermits()+" ");

  28. } catch (InterruptedException e) {

  29. e.printStackTrace();

  30. }finally {

  31. semaphore.release();

  32. }

  33. });

  34. }

  35. executorService.shutdown();

  36. //Semaphore

  37. // final int totalThread =10;

  38. // CyclicBarrier cyclicBarrier=new CyclicBarrier(totalThread);

  39. // ExecutorService executorService=Executors.newCachedThreadPool();

  40. // for(int i=0;i<totalThread;i++){

  41. // executorService.execute(()->{

  42. // System.out.println("before...");

  43. // try{

  44. // cyclicBarrier.wait();//源程序是await,这里只能使用wait

  45. // } catch (InterruptedException e) {

  46. // e.printStackTrace();

  47. // }

  48. // System.out.print("after..");

  49. // });

  50. // executorService.shutdown();

  51. // }

  52. //CountDownLatch实例

  53. // final int totalThread=10;

  54. // CountDownLatch countDownLatch=new CountDownLatch(3);

  55. // ExecutorService executorService= Executors.newCachedThreadPool();

  56. // for(int i=0;i<6;i++){

  57. // int finalI = i;

  58. // Thread.sleep(1000);

  59. // executorService.execute(()->{

  60. // System.out.print(finalI +"run-");

  61. // countDownLatch.countDown();

  62. // });

  63. // }

  64. // new Thread(()->{

  65. // try {

  66. // countDownLatch.await();

  67. // } catch (InterruptedException e) {

  68. // e.printStackTrace();

  69. // }

  70. // System.out.println("await等待线程");

  71. // }).start();

  72. //

  73. // System.out.println("end");

  74. // executorService.shutdown();

  75. }

  76. }

  1. package com.cnblogs.mufasa.demo7;

  2. import java.util.concurrent.ExecutorService;

  3. import java.util.concurrent.Executors;

  4. import java.util.concurrent.Semaphore;

  5. public class SemaphoreExample {

  6. public static void main(String[] args) {

  7. final int clientCount = 3;

  8. final int totalRequestCount = 10;

  9. Semaphore semaphore = new Semaphore(clientCount);

  10. ExecutorService executorService = Executors.newCachedThreadPool();

  11. for (int i = 0; i < totalRequestCount; i++) {

  12. executorService.execute(()->{

  13. try {

  14. semaphore.acquire();

  15. System.out.print(semaphore.availablePermits() + " ");

  16. } catch (InterruptedException e) {

  17. e.printStackTrace();

  18. } finally {

  19. semaphore.release();

  20. }

  21. });

  22. }

  23. executorService.shutdown();

  24. }

  25. }

8、J.U.C-其他组件

样例代码:

  1. package com.cnblogs.mufasa.demo8;

  2. import java.util.concurrent.ExecutionException;

  3. import java.util.concurrent.ForkJoinPool;

  4. import java.util.concurrent.Future;

  5. import java.util.concurrent.RecursiveTask;

  6. public class ForkJoinExample extends RecursiveTask<Integer> {

  7. private final int threshold=5;

  8. private int first;

  9. private int last;

  10. public ForkJoinExample(int first,int last){

  11. this.first=first;

  12. this.last=last;

  13. }

  14. @Override

  15. protected Integer compute() {

  16. int result=0;

  17. if(last-first<=threshold){

  18. //运算量足够小直接计算

  19. for(int i=first;i<=last;i++){

  20. result +=i;

  21. }

  22. }else {

  23. //拆分成小任务

  24. int middle=first+(last-first)/2;

  25. ForkJoinExample leftTask=new ForkJoinExample(first,middle);

  26. ForkJoinExample rightTask=new ForkJoinExample(middle+1,last);

  27. leftTask.fork();

  28. rightTask.fork();

  29. result =leftTask.join()+rightTask.join();

  30. }

  31. return result;

  32. }

  33. public static int sum(int first,int last){

  34. int sum=0;

  35. for(int i=first;i<=last;i++){

  36. sum+=i;

  37. }

  38. return sum;

  39. }

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

  41. //普通方法计算

  42. // System.out.println(sum(1, 1000000000));

  43. //并行计算方法

  44. // ForkJoinExample example = new ForkJoinExample(1, 1000000000);

  45. // ForkJoinPool forkJoinPool = new ForkJoinPool();

  46. // Future result=forkJoinPool.submit(example);

  47. // System.out.println(result.get());

  48. }

  49. }

  1. package com.cnblogs.mufasa.demo8;

  2. import java.util.concurrent.Callable;

  3. import java.util.concurrent.ExecutionException;

  4. import java.util.concurrent.Future;

  5. import java.util.concurrent.FutureTask;

  6. public class FutureTaskExample{

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

  8. FutureTask<Integer> futureTask=new FutureTask<>(new Callable<Integer>() {

  9. @Override

  10. public Integer call() throws Exception {

  11. int result=0;

  12. for(int i=0;i<10;i++){

  13. Thread.sleep(500);

  14. System.out.println("thread-A:"+i);

  15. result +=i;

  16. }

  17. return result;

  18. }

  19. });

  20. Thread computeThread=new Thread(futureTask);

  21. computeThread.start();

  22. Thread otherThread=new Thread(()->{

  23. System.out.println("other task is running...");

  24. try {

  25. Thread.sleep(1000);

  26. } catch (InterruptedException e) {

  27. e.printStackTrace();

  28. }

  29. });

  30. otherThread.start();

  31. System.out.println("运行正常");

  32. System.out.println(futureTask.get());

  33. }

  34. }

  1. package com.cnblogs.mufasa.demo8;

  2. import java.util.concurrent.ArrayBlockingQueue;

  3. import java.util.concurrent.BlockingQueue;

  4. public class ProducerConsumer {

  5. private static BlockingQueue<String> queue=new ArrayBlockingQueue<>(5);

  6. private static class Producer extends Thread{

  7. @Override

  8. public void run() {

  9. try {

  10. queue.put("product");

  11. } catch (InterruptedException e) {

  12. e.printStackTrace();

  13. }

  14. System.out.println(queue.size()+"produce..");

  15. }

  16. }

  17. private static class Consumer extends Thread{

  18. @Override

  19. public void run() {

  20. try {

  21. String product=queue.take();

  22. } catch (InterruptedException e) {

  23. e.printStackTrace();

  24. }

  25. System.out.println(queue.size()+"consume..");

  26. }

  27. }

  28. public static void main(String[] args) {//类似缓存,协调速率

  29. for(int i=0;i<2;i++){

  30. Producer producer=new Producer();

  31. producer.start();

  32. }

  33. for(int i=0;i<5;i++){

  34. Consumer consumer=new Consumer();

  35. consumer.start();

  36. }

  37. for (int i = 0; i < 3; i++) {

  38. Producer producer = new Producer();

  39. producer.start();

  40. }

  41. }

  42. }

9、线程不安全

  1. package com.cnblogs.mufasa.demo9;

  2. import java.util.concurrent.CountDownLatch;

  3. import java.util.concurrent.Executor;

  4. import java.util.concurrent.ExecutorService;

  5. import java.util.concurrent.Executors;

  6. class ThreadUnsafeExample{

  7. private int cnt=0;

  8. // public synchronized void add(){//输出为1000,同步后输出正常

  9. public void add(){//不同步后,输出不正常

  10. cnt++;

  11. }

  12. public int get(){

  13. return cnt;

  14. }

  15. }

  16. public class Client {

  17. public static void main(String[] args) throws InterruptedException {

  18. final int threadSize=1000;

  19. ThreadUnsafeExample example=new ThreadUnsafeExample();

  20. final CountDownLatch countDownLatch=new CountDownLatch(threadSize);

  21. ExecutorService executorService= Executors.newCachedThreadPool();

  22. for(int i=0;i<threadSize;i++){

  23. executorService.execute(()->{

  24. example.add();

  25. countDownLatch.countDown();

  26. });

  27. }

  28. countDownLatch.await();

  29. executorService.shutdown();

  30. System.out.println(example.get());

  31. }

  32. }

10、Java内存模式

  1. package com.cnblogs.mufasa.demo10;

  2. import java.util.concurrent.CountDownLatch;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. import java.util.concurrent.atomic.AtomicInteger;

  6. public class AtomicExample {

  7. private AtomicInteger cnt=new AtomicInteger();

  8. public void add(){

  9. cnt.incrementAndGet();//原子自增

  10. }

  11. public int get(){

  12. return cnt.get();

  13. }

  14. public static void main(String[] args) throws InterruptedException {

  15. final int threadSize=1000;

  16. AtomicExample example=new AtomicExample();

  17. final CountDownLatch countDownLatch=new CountDownLatch(threadSize);

  18. ExecutorService excutorService= Executors.newCachedThreadPool();

  19. for(int i=0;i<threadSize;i++){

  20. excutorService.execute(()->{

  21. example.add();

  22. countDownLatch.countDown();

  23. });

  24. }

  25. countDownLatch.await();

  26. excutorService.shutdown();

  27. System.out.println(example.get());

  28. }

  29. }

  1. package com.cnblogs.mufasa.demo10;

  2. import java.util.concurrent.CountDownLatch;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. public class AtomicSynchronizedExample {

  6. private int cnt=0;

  7. public synchronized void add(){

  8. cnt++;

  9. }

  10. public synchronized int get(){

  11. return cnt;

  12. }

  13. public static void main(String[] args) throws InterruptedException {

  14. final int threadSize = 1000;

  15. AtomicSynchronizedExample example=new AtomicSynchronizedExample();

  16. final CountDownLatch countDownLatch = new CountDownLatch(threadSize);

  17. ExecutorService executorService = Executors.newCachedThreadPool();

  18. for(int i=0;i<threadSize;i++){

  19. executorService.execute(()->{

  20. example.add();

  21. countDownLatch.countDown();

  22. });

  23. }

  24. countDownLatch.await();

  25. executorService.shutdown();

  26. System.out.println(example.get());

  27. }

  28. }

11、线程安全

  1. package com.cnblogs.mufasa.demo11;

  2. import java.util.concurrent.Executor;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. import java.util.concurrent.atomic.AtomicInteger;

  6. public class AtomicIntegerExample {

  7. private AtomicInteger cnt=new AtomicInteger();

  8. public void add(){

  9. cnt.incrementAndGet();

  10. }

  11. public int get(){

  12. return cnt.get();

  13. }

  14. public static void main(String[] args) throws InterruptedException {

  15. AtomicIntegerExample example=new AtomicIntegerExample();

  16. ExecutorService executorService= Executors.newCachedThreadPool();

  17. for(int i=0;i<10;i++){

  18. executorService.execute(()->example.add());

  19. }

  20. Thread.sleep(100);

  21. example.add();

  22. System.out.println(example.get());

  23. executorService.shutdown();

  24. }

  25. }

  1. package com.cnblogs.mufasa.demo11;

  2. import java.util.Collections;

  3. import java.util.HashMap;

  4. import java.util.Map;

  5. public class ImmutableExample {

  6. public static void main(String[] args) {

  7. Map<String,Integer> map=new HashMap<>();

  8. map.put("b",2);

  9. System.out.println(map.get("b"));

  10. Map<String,Integer> unmodifiableMap= Collections.unmodifiableMap(map);//相当于设置一下

  11. System.out.println(unmodifiableMap.get("b"));

  12. unmodifiableMap.put("a",1);

  13. }

  14. }

  1. package com.cnblogs.mufasa.demo11;

  2. import java.util.concurrent.Executor;

  3. import java.util.concurrent.ExecutorService;

  4. import java.util.concurrent.Executors;

  5. public class Stack_closedExample {

  6. public void add100() {

  7. int cnt=0;

  8. for(int i=0;i<100;i++){

  9. cnt++;

  10. }

  11. System.out.println(cnt);

  12. }

  13. public static void main(String[] args) {

  14. Stack_closedExample example=new Stack_closedExample();

  15. ExecutorService executorService= Executors.newCachedThreadPool();

  16. executorService.execute(()->example.add100());

  17. executorService.execute(()->example.add100());

  18. executorService.shutdown();

  19. }

  20. }

  21. package com.cnblogs.mufasa.demo11;

  22. public class ThreadLocalExample {

  23. public static void main(String[] args) {

  24. ThreadLocal threadLocal=new ThreadLocal();

  25. Thread thread1=new Thread(()->{

  26. threadLocal.set(1);

  27. try{

  28. Thread.sleep(1000);

  29. } catch (InterruptedException e) {

  30. e.printStackTrace();

  31. }

  32. System.out.println(threadLocal.get());

  33. threadLocal.remove();

  34. });

  35. Thread thread2=new Thread(()->{

  36. threadLocal.set(2);

  37. threadLocal.remove();

  38. });

  39. thread1.start();

  40. thread2.start();

  41. }

  42. }

  43. package com.cnblogs.mufasa.demo11;

  44. public class ThreadLocalExample1 {

  45. public static void main(String[] args) {

  46. ThreadLocal threadLocal1=new ThreadLocal();

  47. ThreadLocal threadLocal2=new ThreadLocal();

  48. Thread thread1 = new Thread(() -> {

  49. threadLocal1.set(1);

  50. threadLocal2.set(1);

  51. });

  52. Thread thread2 = new Thread(() -> {

  53. threadLocal1.set(2);

  54. threadLocal2.set(2);

  55. });

  56. thread1.start();

  57. thread2.start();

  58. }

  59. }

12、锁优化

  1. package com.cnblogs.mufasa.demo12;

  2. public class StringExample {

  3. public static String concatString(String s1, String s2, String s3) {

  4. return s1 + s2 + s3;

  5. }

  6. public static String concatString1(String s1, String s2, String s3) {

  7. StringBuilder sb = new StringBuilder ();

  8. sb.append(s1);

  9. sb.append(s2);

  10. sb.append(s3);

  11. return sb.toString();

  12. }

  13. public static void main(String[] args) {

  14. System.out.println(concatString("12","34","56"));

  15. System.out.println(concatString1("12","34","56"));

  16. }

  17. }

13、多线程开发良好的实践

来源:https://www.cnblogs.com/Mufasa/p/11430993.html

往期精彩

01 漫谈发版哪些事,好课程推荐

02 Linux的常用最危险的命令

03 互联网支付系统整体架构详解

04 优秀的Java程序员必须了解的GC哪些

05 IT大企业有哪些病,别被这些病毁了自己?

关注我每天进步一点点

你点的在看,我都当成了喜欢

java多线程那些靠谱的总结相关推荐

  1. 面试题汇总二 Java 多线程篇

    前言 题目汇总来源 史上最全各类面试题汇总,没有之一,不接受反驳 面试题汇总一 Java 语言基础篇 面试题汇总二 Java 多线程篇 面试题汇总三 Java 集合篇 面试题汇总四 JVM 篇 面试题 ...

  2. 如何掌握java多线程,高并发,大数据方面的技能?

    https://www.zhihu.com/question/27575123 如何掌握java多线程,高并发,大数据方面的技能? 因为想进入互联网公司,然后发现互联网类型的公司问的主要问题都离不开这 ...

  3. bat 等大厂常问的Java多线程面试题,3万字解析

    1 基本概括 2 文章详情 1.1 Java基础--Java多线程(进程与线程的介绍) 1.2 Java基础--Java多线程(线程的创建方式) 1.3 Java基础--Java多线程(什么是进程?) ...

  4. Java 多线程的基本方式

    Java 多线程的基本方式 基础实现两种方式: 通过实现Callable 接口方式(可得到返回值):

  5. Java多线程读取本地照片为二进制流,并根据系统核数动态确定线程数

    Java多线程读取图片内容并返回 1. ExecutorService线程池 2. 效率截图 3. 源码 1. ExecutorService线程池 ExecutorService线程池,并可根据系统 ...

  6. Java多线程,Thread,Runnable,Callable Task,Future<Task>,CompletionService

    一.Java多线程的方法 1. 继承 Thread 2. 实现 Runnable 3. 实现 Callable 可以有返回值 package com.test;import java.util.Arr ...

  7. 【收藏】Java多线程/并发编程大合集

    (一).[Java并发编程]并发编程大合集-兰亭风雨    [Java并发编程]实现多线程的两种方法    [Java并发编程]线程的中断    [Java并发编程]正确挂起.恢复.终止线程    [ ...

  8. 40个Java多线程问题总结

    (转) 这篇文章作者写的真是不错 40个问题汇总 1.多线程有什么用? 一个可能在很多人看来很扯淡的一个问题:我会用多线程就好了,还管它有什么用?在我看来,这个回答更扯淡.所谓"知其然知其所 ...

  9. Java多线程编程实战:模拟大量数据同步

    背景 最近对于 Java 多线程做了一段时间的学习,笔者一直认为,学习东西就是要应用到实际的业务需求中的.否则要么无法深入理解,要么硬生生地套用技术只是达到炫技的效果. 不过笔者仍旧认为自己对于多线程 ...

  10. Java多线程学习处理高并发问题

    在程序的应用程序中,用户或请求的数量达到一定数量,并且无法避免并发请求.由于对接口的每次调用都必须在返回时终止,因此,如果接口的业务相对复杂,则可能会有多个用户.调用接口时,该用户将冻结. 以下内容将 ...

最新文章

  1. 你哪来这么多事(二):学生信息查找
  2. java注解机制_Java 注解机制
  3. PostgreSQL9.5和JSONB的强大功能
  4. OpenGL几何着色器
  5. 有人WIFI模块使用详解
  6. 如何通过代码获得当前SAP Spartacus Component渲染所基于的slot名称
  7. 如何理解np.sum tf.reduce_sum( tf.reduce_max tf.reduce_mean)等对tensor和高维矩阵的axis选择的操作
  8. 计算机编程结束进程代码,M代码如何停止CNC编程的程序
  9. linux下运行程序后出现段错误的原因和解决案例
  10. python 代码替换_用Python将绝对URL替换成相对URL的代码
  11. a标签加onclick点击事件
  12. vs2017 Visual Studio 离线安装方法
  13. Java--工厂模式
  14. 配置元件--HTTP授权管理器
  15. 台州市建筑物矢量数据(Shp格式+带高度)
  16. QCIF CIF 2CIF 4CIF 普及
  17. 汇编环境搭建 -- MASM32
  18. 直播特效的实现原理与难点
  19. ie浏览器html播放器,ie浏览器播放不了网页视频
  20. 创建自己的腾讯云存储桶,将图片上传到腾讯云,并实现父子之间的数据双向绑定

热门文章

  1. 用u盘装linux系统黑屏,u盘启动黑屏 u盘装系统启动不了黑屏咋办
  2. php动态效果,jquery+php实现动态数字显示效果
  3. VMware虚拟机安装Kali破解WiFi密码
  4. 【Python从入门到精通】(一)就简单看看Python吧
  5. 通往区块链的最后一张船票
  6. ES--highlight(高亮)查询
  7. 解非齐次线性方程组c语言,解非齐次线性方程组C语言程序设计.pdf
  8. 基于PHP的校园竞赛信息网站 毕业设计-附源码221230
  9. pentaho资源库迁移-MySQL
  10. 云服务器ubuntu建网站,云服务器ubuntu建网站