In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to create threads in Java multithreading, which is very detailed and has a certain reference value. Friends who are interested must finish it!
First, three creation methods based on what to create the Thread class inherits the Thread class Runnable interface to implement the Runnable interface callable interface to implement the callable interface 2.2.1steps to create through the Thread class
The custom thread class inherits the Thread class
Override the run () method to write the thread execution body (used as the main () method)
Create a thread object and call the start () method to start the thread
2.2 case
Create two threads, one of which prints an even number within 100 and the other thread prints an odd number within 100
/ / the main method public class Demo01 {public static void main (String [] args) {Thread1 thread1 = new Thread1 (); Thread2 thread2 = new Thread2 (); thread1.start (); thread2.start ();}} / / even class Thread1 extends Thread {@ Override public void run () {for (int I = 0; I)
< 100; i++) { if (i%2==0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } }}//100以内的奇数class Thread2 extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { if (i%2!=0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } }} 也可以使用匿名内部类的方法来实现(线程用过以后就不再用了) public class Demo02 { public static void main(String[] args) { //打印0~100内的偶数 new Thread(){ @Override public void run() { for (int i = 0; i < 100; i++) { if (i%2==0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } }.start(); //打印0~100内的奇数 new Thread(){ @Override public void run() { for (int i = 0; i < 100; i++) { if (i%2!=0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } }.start(); }} 三个窗口同时卖票,票数总共为100张(注意票数应该是静态变量,否则就是没创建一个对象,该对象就有100张票) public class Test { public static void main(String[] args) { Window w1 = new Window("窗口 1 "); Window w2 = new Window("窗口 2 "); Window w3 = new Window("窗口 3 "); w1.start(); w2.start(); w3.start(); }}class Window extends Thread{ //这里票的数量应该是静态变量,否则每个对象创建后都有100张票,而不是总共100张票 private static int tickets = 100; public Window(String name) { super(name); } @Override public void run() { while (tickets >0) {tickets--; System.out.println (getName () + "sold a ticket, remaining number of votes:" + tickets);}
Note: there is a thread safety issue that has not been resolved, which will be discussed later. As shown in the following figure, when the first three threads started, the number of votes read was 100.
2.3 issues to pay attention to
The function of the start () method: start the thread by calling the start () method of the thread class object written by yourself, and call the thread's run () method
You cannot start a thread by calling the run () method directly
You cannot let a thread that has already start () star () again to run two threads at the same time. You can create a new object of the thread class, and then start () the newly created object
Third, the methods commonly used in Thread class
Start () starts the current thread; calls the current thread's run () method
Run (): you usually need to override this method in the Thread class to declare the operation that the creation thread needs to perform in this method (used as main ())
CurrentThread (): static method that returns the thread executing the current code
GetName (): gets the name of the current thread
SetName (String name): sets the name of the current thread
Yield (): release the execution power of the current CPU (but it is also possible that the execution power of the next moment will return to the current thread, and the main control will still be in the hands of CPU)
Join (): call the join () of thread b in thread a, and thread an enters the blocking state until thread b finishes execution, and thread an ends the blocking state.
Stop (): forces the current thread to end when this method is executed (disabled)
Sleep (int millitime): lets the current thread "sleep" the specified millitime milliseconds. The current process is in a blocking state within the specified millitime millisecond
IsAlive (): determines whether the current thread is alive (until the thread finishes execution)
3.1 case
It is the same problem of buying tickets in the above three windows, which is also 100 tickets, but using this method of creation, tickets can not use static variables.
Create thread 4.1 creation steps by implementing the Runnable interface
Create a class that implements the Runnable interface
The implementation class implements the abstract method in the Runnable interface: run ()
Create an object that implements the class
Pass this object as a parameter to the constructor of the Thread class to create an object of the Thread class
Call start () through the object of the Thread class
Start () here starts the current thread first, and then calls run () of target of type Runnable.
5. Comparison between inheriting Thread class and implementing Runnable interface.
In development, priority is given to creating threads by implementing the Runnable interface.
Reason:
The Runnable interface is implemented without the limitation of single inheritance of a class (a class can only inherit one parent class, and a Thread class cannot inherit other classes)
The implementation of the Runnable interface is more appropriate to deal with situations where data is shared between multiple threads
Contact: the Thread class itself also implements the Runnable interface
Similarities: both methods require overriding the run () method to declare the logic to be executed by the thread in the run () method
VI. Priority setting of threads
Scheduling strategy
For threads with the same priority, form a first-in, first-out queue (first-come-first-out service) and use the time slice strategy
For high priority, use the preemptive mode of priority scheduling
The priority of a thread is divided into 10 files from 1 to 10, where:
NORM_PRIORITY:5-normal priority, the default priority
MAX_PRIORITY:10-highest priority
MIN_PRIORITY:1-lowest priority
GetPriority (): gets the priority of the thread
SetPriority (int p): sets the priority of a thread
Note: the higher priority thread preempts the execution power of the lower priority thread CPU. But only in terms of probability, high-priority threads are executed with a high probability. This does not mean that low-priority threads will be executed only after the high-priority threads have been executed.
These are all the contents of the article "how to create threads in Java multithreading". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.