There are four ways to create threads in Java, four ways to create threads in Java

Sweet potato 2021-04-16 12:21:51
ways create threads java ways


 

Java Multithreading ,Java Create thread 4 Ways of planting ,Java Four ways to create threads

 

================================

Copyright Sweet potato  2021-04-16

https://www.cnblogs.com/fanshuyao/

 

One 、Java Four ways to create threads

1、 Inherit  Thread class

public class Threadable extends Thread{
@Override
public void run() {
System.out.println("Threadable The current thread is :" + Thread.currentThread().getName());
}
}

 

2、 Realization Runnable Interface

public class ThreadRun implements Runnable{
@Override
public void run() {
System.out.println("ThreadRun The current thread is :" + Thread.currentThread().getName());
}
}

 

Realization Runnable Interfaces and inheritance Thread Class differences :

  • synchronized(this) Use in this when ,this Is the current object , Inherit Thread Class to create multiple threads ,this It's different , There will be problems . Realization Runnable Interface because there's only one , So no problem .
  • synchronized(obj): You can create one in the thread class obj object , Represents a thread shared object , In this way, the object to be locked is the same . It should be noted that : Realization Runnable Interface creates objects without adding static, Inherit Thread Class must add static, Otherwise, the object is not the same .
  • synchronized(XXX.class): Use class , Class has only one , Can solve synchronized(obj) The problem of ( Inherit Thread Class must add static). stay Java in , Everything is regarded as an object , So classes are OK .

So in general , Construction, use and realization Runnable How to interface , Avoid inheritance Thread The problem is .

 

3、 Realization  Callable<V>  Interface

import java.util.concurrent.Callable;
public class ThreadCallable implements Callable<Object> {
@Override
public Object call() throws Exception {
return null;
}
}

And the implementation  Runnable The difference between interfaces is :

  • Callable You can throw anomalies out
  • Callable There is a return value

 

4、 Use thread pool to create

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadTest5Executors {
public static void main(String[] args) {
ThreadRunData threadRun = new ThreadRunData();
// Creating a thread pool , There's something in the pool 10 Threads 
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(threadRun);//execute It didn't come back 
executorService.execute(threadRun);//execute It didn't come back 
executorService.submit(threadRun);//submit There is a return 
executorService.submit(threadRun);//submit There is a return
//executorService.submit(task);//submit There is a return , If you use Callable And there is a return value , You need to use submit
// Close thread pool 
 executorService.shutdown();
}
}

 

 

Two 、Java  Multithreading Synchronized Keyword use

synchronized(object object )

  • synchronized(this):this Represents the current object of the call
  • synchronized(obj): You can create one in the thread class obj object , Represents a thread shared object , In this way, the object to be locked is the same . It should be noted that : Realization Runnable Interface creates objects without adding static, Inherit Thread Class must add static, Otherwise, the object is not the same .
  • synchronized(XXX.class): Use class , Class has only one , Can solve synchronized(obj) The problem of ( Inherit Thread Class must add static). stay Java in , Everything is regarded as an object , So classes are OK .

 

1、 By implementing Runnable Interface create thread class

public class ThreadRunData implements Runnable{
private int ticket = 30;
@Override
public void run() {
while(true) {
synchronized(this) {
if(ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadRunData " + Thread.currentThread().getName() + ": Sell No " + ticket + " ticket ");
ticket--;
}else {
System.out.println("ThreadRunData " + Thread.currentThread().getName() + ": Sold Out ");
break;
}
}
}
}
}

 

2、 Multi thread ticket selling , The common data is ticket

public class ThreadTest2 {
public static void main(String[] args) {
ThreadRunData threadRun = new ThreadRunData();
Thread thread = new Thread(threadRun);
thread.setName(" Thread one ");
thread.start();
Thread thread2 = new Thread(threadRun);
thread2.setName(" Thread two ");
thread2.start();
Thread thread3 = new Thread(threadRun);
thread3.setName(" Line 3 ");
thread3.start();
Thread thread4 = new Thread(threadRun);
thread4.setName(" Thread 4 ");
thread4.start();
}
}

 

result :

Not added synchronized Keyword before :

Existing problems :

  • Tickets are sold repeatedly
  • Tickets are oversold
ThreadRunData The current thread is : Thread two , Sell No 30 ticket
ThreadRunData The current thread is : Line 3 , Sell No 30 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 30 ticket
ThreadRunData The current thread is : Thread one , Sell No 30 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 26 ticket
ThreadRunData The current thread is : Thread one , Sell No 26 ticket
ThreadRunData The current thread is : Thread two , Sell No 26 ticket
ThreadRunData The current thread is : Line 3 , Sell No 26 ticket
ThreadRunData The current thread is : Thread two , Sell No 22 ticket
ThreadRunData The current thread is : Line 3 , Sell No 22 ticket
ThreadRunData The current thread is : Thread one , Sell No 22 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 22 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 18 ticket
ThreadRunData The current thread is : Thread two , Sell No 18 ticket
ThreadRunData The current thread is : Thread one , Sell No 18 ticket
ThreadRunData The current thread is : Line 3 , Sell No 18 ticket
ThreadRunData The current thread is : Line 3 , Sell No 14 ticket
ThreadRunData The current thread is : Thread two , Sell No 14 ticket
ThreadRunData The current thread is : Thread one , Sell No 14 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 14 ticket
ThreadRunData The current thread is : Thread two , Sell No 10 ticket
ThreadRunData The current thread is : Line 3 , Sell No 10 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 10 ticket
ThreadRunData The current thread is : Thread one , Sell No 10 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 6 ticket
ThreadRunData The current thread is : Thread two , Sell No 6 ticket
ThreadRunData The current thread is : Line 3 , Sell No 6 ticket
ThreadRunData The current thread is : Thread one , Sell No 6 ticket
ThreadRunData The current thread is : Line 3 , Sell No 2 ticket
ThreadRunData The current thread is : Thread one , Sell No 2 ticket
ThreadRunData The current thread is : Thread one , Sold Out
ThreadRunData The current thread is : Thread two , Sell No 2 ticket
ThreadRunData The current thread is : Thread two , Sold Out
ThreadRunData The current thread is : Thread 4 , Sell No 2 ticket
ThreadRunData The current thread is : Thread 4 , Sold Out
ThreadRunData The current thread is : Line 3 , Sell No -2 ticket
ThreadRunData The current thread is : Line 3 , Sold Out 

 

added synchronized After keyword :

Solved the problem above .

ThreadRunData The current thread is : Thread one , Sell No 30 ticket
ThreadRunData The current thread is : Thread one , Sell No 29 ticket
ThreadRunData The current thread is : Thread one , Sell No 28 ticket
ThreadRunData The current thread is : Thread one , Sell No 27 ticket
ThreadRunData The current thread is : Thread one , Sell No 26 ticket
ThreadRunData The current thread is : Thread one , Sell No 25 ticket
ThreadRunData The current thread is : Thread one , Sell No 24 ticket
ThreadRunData The current thread is : Thread one , Sell No 23 ticket
ThreadRunData The current thread is : Thread one , Sell No 22 ticket
ThreadRunData The current thread is : Thread one , Sell No 21 ticket
ThreadRunData The current thread is : Thread one , Sell No 20 ticket
ThreadRunData The current thread is : Thread one , Sell No 19 ticket
ThreadRunData The current thread is : Thread one , Sell No 18 ticket
ThreadRunData The current thread is : Thread one , Sell No 17 ticket
ThreadRunData The current thread is : Thread one , Sell No 16 ticket
ThreadRunData The current thread is : Thread one , Sell No 15 ticket
ThreadRunData The current thread is : Thread one , Sell No 14 ticket
ThreadRunData The current thread is : Thread one , Sell No 13 ticket
ThreadRunData The current thread is : Thread one , Sell No 12 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 11 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 10 ticket
ThreadRunData The current thread is : Thread 4 , Sell No 9 ticket
ThreadRunData The current thread is : Line 3 , Sell No 8 ticket
ThreadRunData The current thread is : Line 3 , Sell No 7 ticket
ThreadRunData The current thread is : Line 3 , Sell No 6 ticket
ThreadRunData The current thread is : Line 3 , Sell No 5 ticket
ThreadRunData The current thread is : Line 3 , Sell No 4 ticket
ThreadRunData The current thread is : Line 3 , Sell No 3 ticket
ThreadRunData The current thread is : Thread two , Sell No 2 ticket
ThreadRunData The current thread is : Thread two , Sell No 1 ticket
ThreadRunData The current thread is : Thread two , Sold Out
ThreadRunData The current thread is : Line 3 , Sold Out
ThreadRunData The current thread is : Thread 4 , Sold Out
ThreadRunData The current thread is : Thread one , Sold Out 

 

3、 ... and 、Java  Multithreading ReentrantLock Use

ReentrantLock  Lock and synchronized The difference between :

  • ReentrantLock To lock and release the lock manually ;synchronized Keywords can be in code blocks or methods , Automatically release the lock after running , Avoid forgetting to release the lock , Formation of a deadlock
  • ReentrantLock You can try to get the lock , After multiple acquisitions , You can terminate and release the lock ;synchronized Will be waiting .

General situation , Recommended or used synchronized Well .

 

1、 Use... In threads ReentrantLock  Lock

import java.util.concurrent.locks.ReentrantLock;
public class ThreadRunDataLock implements Runnable{
private int ticket = 30;
private ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
while(true) {
try {
// Lock 
 reentrantLock.lock();
if(ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadRunData " + Thread.currentThread().getName() + ": Sell No " + ticket + " ticket ");
ticket--;
}else {
System.out.println("ThreadRunData " + Thread.currentThread().getName() + ": Sold Out ");
break;
}
}finally {
// Release the lock 
 reentrantLock.unlock();
}
}
}
}

 

2、 Create multiple thread calls

public class ThreadTest4Lock {
public static void main(String[] args) {
ThreadRunDataLock threadRun = new ThreadRunDataLock();
Thread thread = new Thread(threadRun);
thread.setName(" Thread one ");
thread.start();
Thread thread2 = new Thread(threadRun);
thread2.setName(" Thread two ");
thread2.start();
Thread thread3 = new Thread(threadRun);
thread3.setName(" Line 3 ");
thread3.start();
Thread thread4 = new Thread(threadRun);
thread4.setName(" Thread 4 ");
thread4.start();
}
}

 

Four 、 Two threads run alternately

1、 Thread class : Alternate operation

/**
* Thread one 、 Thread two sells tickets alternately
* @author liqiongy
*
*/
public class ThreadRunDataAlternate implements Runnable{
private int ticket = 30;
@Override
public void run() {
while(true) {
synchronized(this) {
// Wake up another thread waiting . There are multiple waiting threads, and only one , Because only 2 Threads , So it must be another one that wakes up 
this.notify();
if(ticket > 0) {
try {
// Thread sleep , Do not release locks and resources 
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadRunData " + Thread.currentThread().getName() + ": Sell No " + ticket + " ticket ");
ticket--;
try {
// Thread waiting , Release locks and resources 
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
System.out.println("ThreadRunData " + Thread.currentThread().getName() + ": Sold Out ");
break;
}
}
}
}
}

 

2、 Create two thread tests :

public class ThreadTest3Alternate {
public static void main(String[] args) {
ThreadRunDataAlternate threadRun = new ThreadRunDataAlternate();
Thread thread = new Thread(threadRun);
thread.setName(" Threads 1");
thread.start();
Thread thread2 = new Thread(threadRun);
thread2.setName(" Thread two ");
thread2.start();
}
}

 

3、 result :

ThreadRunData Threads 1: Sell No 30 ticket
ThreadRunData Thread two : Sell No 29 ticket
ThreadRunData Threads 1: Sell No 28 ticket
ThreadRunData Thread two : Sell No 27 ticket
ThreadRunData Threads 1: Sell No 26 ticket
ThreadRunData Thread two : Sell No 25 ticket
ThreadRunData Threads 1: Sell No 24 ticket
ThreadRunData Thread two : Sell No 23 ticket
ThreadRunData Threads 1: Sell No 22 ticket
ThreadRunData Thread two : Sell No 21 ticket
ThreadRunData Threads 1: Sell No 20 ticket
ThreadRunData Thread two : Sell No 19 ticket
ThreadRunData Threads 1: Sell No 18 ticket
ThreadRunData Thread two : Sell No 17 ticket
ThreadRunData Threads 1: Sell No 16 ticket
ThreadRunData Thread two : Sell No 15 ticket
ThreadRunData Threads 1: Sell No 14 ticket
ThreadRunData Thread two : Sell No 13 ticket
ThreadRunData Threads 1: Sell No 12 ticket
ThreadRunData Thread two : Sell No 11 ticket
ThreadRunData Threads 1: Sell No 10 ticket
ThreadRunData Thread two : Sell No 9 ticket
ThreadRunData Threads 1: Sell No 8 ticket
ThreadRunData Thread two : Sell No 7 ticket
ThreadRunData Threads 1: Sell No 6 ticket
ThreadRunData Thread two : Sell No 5 ticket
ThreadRunData Threads 1: Sell No 4 ticket
ThreadRunData Thread two : Sell No 3 ticket
ThreadRunData Threads 1: Sell No 2 ticket
ThreadRunData Thread two : Sell No 1 ticket
ThreadRunData Threads 1: Sold Out
ThreadRunData Thread two : Sold Out 

 

( If the article helps you , Donations are welcome ,^_^)

 

 

================================

Copyright Sweet potato  2021-04-16

https://www.cnblogs.com/fanshuyao/

版权声明
本文为[Sweet potato]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210416115235927M.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云