当前位置:网站首页>Four ways to create multithreads
Four ways to create multithreads
2022-06-30 06:18:00 【Java shaping】
Catalog
Mode one : Inherit Thread Kind of the way
Mode two 、 Realization Runnable How to interface
Mode three : Realization Callable How to interface Jdk5.0 Newly added
Mode 4 : How to use thread pool
summary : These do not consider whether the thread is safe , So the next chapter considers
Program 、 Threads 、 process
Program : A piece of static code process : A running program Threads : Processes can be refined into threads , It's an execution path inside the program
Mode one : Inherit Thread Kind of the way
step : Create an inheritance from Thread Subclasses of classes rewrite run() Method ---> Write what this thread will do in the method body Create subclass objects Call... Through this object start()
// Traverse 100 An even number within
class MyThread extends Thread {
@Override
// The execution of another thread
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
class W {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}Mode two 、 Realization Runnable How to interface
step : Created and implemented Runnable The class of the interface Implement classes to implement Runnable Abstract methods in interfaces :run() Create objects that implement classes Pass this object as an argument to Thread In the constructor of class , establish Thread Class object adopt Thread Class object call start() Method
class MThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);// It has to be written like this
// Because this implementation class is implemented Runnable, It doesn't have getName() Methods
}
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
// 3. Create objects that implement classes
MThread mThread = new MThread();
// 4. Pass this object as an argument to Thread In the constructor of class , establish Thread Class object
Thread t1 = new Thread(mThread);
// Open another thread
Thread t2 = new Thread(mThread);
t1.setName(" Thread one ");
t2.setName(" Thread two ");
// 5. adopt Thread Class object call start() Method
t1.start();
t2.start();
}
}Mode three : Realization Callable How to interface Jdk5.0 Newly added
step : 1. Create an implementation Callable Implementation class of interface 2. Realization call(), Write the operations that the thread needs to implement in call() in 3. Create objects that implement classes 4. Pass the object of the implementation class as a parameter to FutureTask In the constructor of class , establish FutureTask Class object 5. take FutureTask Object passed as a parameter to Thread In the constructor of class , establish Thread Class and call start(). 6. If you want to call() The return value of , Just use FutureTask Class to call get() To get call() Return value in
class NewThread implements Callable {
// 2. Realization call(), Write the operations that the thread needs to implement in call() in
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
sum += i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
// 3. Create objects that implement classes
NewThread n = new NewThread();
// 4. Pass the object of the implementation class as a parameter to FutureTask In the constructor of class , establish FutureTask Class object
FutureTask f1 = new FutureTask(n);
// 5. take FutureTask Object passed as a parameter to Thread In the constructor of class , establish Thread Class and call start().
new Thread(f1).start();
// 6. If you want to call() The return value of , Just use FutureTask Class to call get() To get call() Return value in
try {//get() The return value of FutureTask The constructor parameter of the Callable The implementation class of call() The value returned
Object sum = f1.get();
System.out.println(sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}Mode 4 : How to use thread pool
step : 1. Create an implementation Runnable perhaps Callable Implementation class of 2. Realization run() or call() 3. Provides a thread pool with a specified number of threads If you need to operate on the thread pool , Forced to ThreadPoolExecutor Type and instantiate . Then you can operate 4. Execute the operation of the specified thread , You need to provide an implementation Runnable perhaps Callable Interface implementation class object 5. Close connection pool
class Thread1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
// 1. Provides a thread pool with a specified number of threads
ExecutorService e = Executors.newFixedThreadPool(10);
// When you need to operate on the thread pool , Forced to ThreadPoolExecutor Type and instantiate . Then you can operate
ThreadPoolExecutor e1 = (ThreadPoolExecutor) e;
e1.setCorePoolSize(19);
// 2. Execute the operation of the specified thread , You need to provide an implementation Runnable perhaps Callable Interface implementation class object
e.execute(new Thread1());// Apply to Runnable
e.execute(new Thread2());// Apply to Runnable
// e.submit();// Apply to Callable
// 3. Close connection pool
e.shutdown();
}
}summary : These do not consider whether the thread is safe , So the next chapter considers
边栏推荐
- Ultra simple STM32 RTC alarm clock configuration
- 网络基础知识
- Docker is equipped with the latest MySQL image
- [OSPF] comparison between rip and OSPF
- Es6数组
- C language final experiment report (student achievement management system) source code
- Decompilation normal decompilation problems. Solve them yourself
- 583. deleting two strings - Dynamic Planning
- IP TCP UDP network encryption suite format
- DHCP operation
猜你喜欢

Learn fpga---ram IP core and key parameters from the bottom structure

重构之美:当多线程批处理任务挑起大梁 - 万能脚手架

Application of redis client list in practice

Beauty of Refactoring: when multithreaded batch processing task lifts the beam - Universal scaffold

DHCP operation

IP TCP UDP network encryption suite format

MySQL日志管理、数据备份、恢复

圖像處理7-圖像增强

飞升:基于中文分词器IK-2种自定义热词分词器构建方式showcase & 排坑showtime

接口中方法详解
随机推荐
从底层结构开始学习FPGA----RAM IP核及关键参数介绍
拼多多店铺搜索相关问题,为什么新品上架搜索不到
Go common judgments
多线程进阶篇
Idea add database
Title: enter two positive integers m and N to find their maximum common divisor and minimum common multiple
ES6 array
Learn fpga---ram IP core and key parameters from the bottom structure
观察者模式、状态模式在实际工作中的使用
Uniapp wechat applet returns to the previous page and refreshes
MySQL事物
To: k210 realizes face recognition (code interpretation attached)
Problems related to pinduoduo store search, why can't new products be found on the shelves
Usage of case, casez and casex statements in Verilog
Common address collection
Completabilefuture: from understanding to mastering, here are all you want to know
Rhcsa day 3
Idea run SQL file
46. 全排列-dfs双百代码
Simple example of class template