Multithreading - Creation of threads
How to create threads
Let’s summarize how to create multi-threads. There are four ways to implement multi-threads. Next, we will talk about the creation methods in detail
1. Inherit the Thread class, and then override the run() method
2. Implement the Runnable interface, and then override the run() method
3. Implement the callable interface, and then override the call< v>Method
4. Thread pool (discussed later, because it is more complicated)
Note: No matter which method is used to create a thread, start the thread using the start provided by the Thread class. ()method.
1. Inherit the Thread class and override the run method
class MyThread extends Thread { private String title; private int ticket = 20; public MyThread(String title) { this.title = title; } public void run() { //放每个线程的子任务 while (ticket > 0) { System.out.println("当前线程为"+title+",还剩下"+ticket--+"票"); } } } public class ThreadTest { public static void main(String[] args) { MyThread myThread1 = new MyThread("黄牛A"); MyThread myThread2 = new MyThread("黄牛B"); MyThread myThread3 = new MyThread("黄牛C"); myThread1.start(); myThread2.start(); myThread3.start(); } }
2. Implement the Runnable interface and override the run method
class MyRunnable implements Runnable{ @Override public void run() { for(int i =0;i <10;i++){ System.out.println(Thread.currentThread().getName()+"、i="+i); } } } public class RunnableTest { public static void main(String[] args) { Runnable runnable =new MyRunnable(); //向上转型 new Thread(runnable,"线程A").start(); //设置线程名字 new Thread(runnable).start(); //没有设置线程名字,则是系统默认从 Thread-(0,1,2...) Thread thread1 = new Thread(runnable); thread1.setName("线程B"); //调用setName()设置名字 thread1.start(); } }
Here are the three ways to create thread names:
(1) Add the name directly after the brackets
(2) Call setName() to set Name
(3) If no name is set, the system defaults to Thread-(0,1,2....)
3. Implement the Callable interface and override the call
class MyCallable implements Callable<String>{ private int ticket =20; @Override public String call() throws Exception { while(ticket > 0){ System.out.println(Thread.currentThread().getName()+"还剩下"+ticket--+"票"); } return "票卖完了,再见"; } } public class CallableTest { public static void main(String[] args) throws ExecutionException, InterruptedException { //产生Callable对象 MyCallable myCallable = new MyCallable(); //产生FutureTask对象 FutureTask futureTask = new FutureTask(myCallable); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); //接收Callable对象的返回值 } }
1. First generate a Callable object
2. Generate a FutureTask object
3. Create a Thread pass Enter the FutureTask object
4. The return value received from the Callable interface is the get() method in Future
Comparison of three ways to create threads
1 .Inheriting the Thread class has the limitation of single inheritance. Relatively speaking, implementing the Runnable interface is more flexible, and the Thread class itself also implements the Runnable interface to assist the real thread class
2. Implementing the Runnable interface can better realize program sharing Concept
3. The Callable interface is used when a return value is required
If there are obvious errors in the above content, please point it out, I would be grateful. Thanks!
For more related content, please visit the PHP Chinese website: JAVA Video Tutorial
The above is the detailed content of Multithreading - Creation of threads. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



8-core means that the CPU has 8 physical cores, and 16-thread means that the CPU can have up to 16 threads processing tasks at the same time. The number of cores and threads are important performance indicators of a computer CPU. The higher the number of cores of the CPU, the higher the processing speed; the higher the number of threads, the more conducive it is to running multiple programs at the same time, because the number of threads is equivalent to the number of times the CPU can run at the same time at a certain moment. The number of tasks to be processed in parallel. Multi-threading can maximize wide-issue, out-of-order superscalar processing, improve the utilization of processor computing components, and alleviate memory access delays caused by data correlation or cache misses.

To avoid thread starvation, you can use fair locks to ensure fair allocation of resources, or set thread priorities. To solve priority inversion, you can use priority inheritance, which temporarily increases the priority of the thread holding the resource; or use lock promotion, which increases the priority of the thread that needs the resource.

Thread termination and cancellation mechanisms in C++ include: Thread termination: std::thread::join() blocks the current thread until the target thread completes execution; std::thread::detach() detaches the target thread from thread management. Thread cancellation: std::thread::request_termination() requests the target thread to terminate execution; std::thread::get_id() obtains the target thread ID and can be used with std::terminate() to immediately terminate the target thread. In actual combat, request_termination() allows the thread to decide the timing of termination, and join() ensures that on the main line

Differences: 1. A thread can have multiple coroutines, and a process can also have multiple coroutines alone; 2. Threads are a synchronization mechanism, while coroutines are asynchronous; 3. Coroutines can retain the state of the last call, Threads do not work; 4. Threads are preemptive, while coroutines are non-preemptive; 5. Threads are divided CPU resources, and coroutines are organized code processes. Coroutines require threads to host and run.

"Thread" is the smallest unit of instruction flow when a program is running. A process refers to a program with certain independent functions, and a thread is a part of the process, describing the execution status of the instruction flow; the thread is the smallest unit of the instruction execution flow in the process, and is the basic unit of CPU scheduling. A thread is an execution process of a task (a program segment); a thread does not occupy memory space, it is included in the memory space of the process. Within the same process, multiple threads share the process's resources; a process has at least one thread.

During the development of JavaFX applications, we often encounter JavaFX thread stuck errors. Such errors vary in severity and may adversely affect program stability and performance. In order to ensure the normal operation of the program, we need to understand the causes and solutions of JavaFX thread stuck errors, and how to prevent this error from occurring. 1. The cause of JavaFX thread stuck error. JavaFX is a multi-threaded UI application framework, which allows programs to execute for a long time in background threads.

Processes and threads in Go language: Process: an independently running program instance with its own resources and address space. Thread: An execution unit within a process that shares process resources and address space. Features: Process: high overhead, good isolation, independent scheduling. Threads: low overhead, shared resources, internal scheduling. Practical case: Process: Isolating long-running tasks. Threads: Process large amounts of data concurrently.

Microsoft apparently won't keep its powerful AI-powered Copilot tool as an exclusive feature of the new app. Now, the company has just announced plans to bring Copilot to the Outlook classic app on Windows. As posted on its 365 Roadmap website, previews will begin in March next year and will roll out globally on desktops in the current channel until March. Copilot is a productivity tool that uses large language models (LLMs) to help users with tasks such as writing emails, summarizing documents, and translating languages. One of its main features is its ability to summarize emails
