当前位置:网站首页>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
边栏推荐
- MySQL数据库用户管理
- Unable to read file for extraction: gdx64. dll
- 重构之美:当多线程批处理任务挑起大梁 - 万能脚手架
- 谁不想要一个自己的博客网站呢 - 搭建博客网站wordpress
- Intelligent question - horse racing question
- 股票在网上开户安全吗?在网上能不能开户炒股呢?
- A complete performance test process
- Master slave synchronization of MySQL database to realize read-write separation
- Mysql database learning notes - foreign keys, table connections, subqueries, and indexes for MySQL multi table queries
- HCIA day 1
猜你喜欢
![[OSPF] comparison between rip and OSPF](/img/72/00e3a05bc5de0e5a66b4675d030911.jpg)
[OSPF] comparison between rip and OSPF

Usage of case, casez and casex statements in Verilog

Who doesn't want a blog site of their own - build a blog site WordPress

SHELL

观察者模式、状态模式在实际工作中的使用

Centos8 install redis

Golang's handwritten Web Framework

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

Master slave synchronization of MySQL database to realize read-write separation

MySQL存储系统
随机推荐
How to use unmarshaljson
MySQL advanced SQL statement
ES6 array traversal and Es5 array traversal
[MD editing required] welcome to the CSDN markdown editor
ES6 extended operator (...)
Use and principle of completionservice (source code analysis)
VIM view file code
Official win 10 image download
Beauty of Refactoring: when multithreaded batch processing task lifts the beam - Universal scaffold
MySQL transaction
[deep learning] data segmentation
583. deleting two strings - Dynamic Planning
Is it safe to open an account online? Can you open an account to speculate on the Internet?
Spin official tutorial
MySQL高级SQL语句
MySQL數據庫用戶管理
MySQL事物
requests. The difference between session () sending requests and using requests to send requests directly
VLAN access mode
Installation and initialization of MariaDB database