Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Thread class in Java and what its properties are

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to use the Thread class in Java and what its properties are". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the Thread class in Java and what its properties are.

Multithreaded programming can be done in java, and a Thread class is provided in the java standard library to represent thread operations. The Thread class can be regarded as a set of API for multithreaded programming provided by the java standard library.

The created Thread instance corresponds to the threads in the operating system one by one. The operating system provides API (C language style) about threads, and java encapsulates it into a Thread class.

Method 1: inherit the Thread class class MyThread extends Thread {@ Override public void run () {/ / only define a thread class to handle at this time, no new thread has always been created in the system. System.out.println ("hello thread");}} public class TestDemo11 {public static void main (String [] args) {/ / create thread Thread t = new MyThread (); / / start the thread and create a new thread in the system t.start ();}}

Concurrent execution between threads

Class MyThread3 extends Thread {@ Override public void run () {/ / defines a thread class while (true) {System.out.println ("hello thread"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () } public class TestDemo13 {public static void main (String [] args) {Thread t = new MyThread3 (); t.start (); / start t thread while (true) {System.out.println ("hello main"); try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();}

We can see that 1s enters the blocking state after executing the code in a thread, so which thread should be awakened the next second?

We can see that the order of the logs printed out of the two threads of execution is uncertain. After each round, one second later, it is uncertain whether to wake up the thread or the mainthread. (preemptive execution), for the operating system, the order in which threads are scheduled macroscopically is random.

The Thread.sleep () method is explained here, and the sleep () method is not so accurate at the ms level. When this method is called, the thread is forced to block (sleep), but when the blocking time is over, the thread does not continue to execute on cup immediately, if Thread.sleep (1000), after passing 1 second, the blocking time ends, but in 1001ms, the thread may not execute immediately. Maybe the cup in the operating system is busy with other threads. Maybe the thread does not execute until 1006ms.

Method 2: implementing the run () method / / Runnable in the Runnable interface actually describes a task / / creates a class, implements the Runnable interface, and overrides the run method in the Runnable class. In the run () method, it describes which tasks the thread wants to point to. Class MyThread2 implements Runnable {@ Override public void run () {System.out.println ("hello thread");}} public class TestDemo12 {public static void main (String [] args) {/ / create thread, pass the created Runnable instance to Thread instance Thread t = new Thread (new MyThread2 ()); t.start ();} method 3: use inner class

Method 3 is actually a replica of method one, which changes the above two kinds of code into anonymous inner classes.

Public class TestDemo14 {public static void main (String [] args) {Thread T1 = new MyThread () {@ Override public void run () {System.out.println ("hello thread1");}} Thread T2 = new Thread (new Runnable () {@ Override public void run () {System.out.println ("hello thread2");}}); t1.start (); t2.start ();}}

Method 4: using the lambmd expression public class TestDemo15 {public static void main (String [] args) {/ / is actually using the lambad expression instead of Runnable Thread T1 = new Thread (()-> {/ / () for the no-parameter run () method System.out.println ("hello thread1");});}} the benefits of using threads

In order to more conveniently reflect the benefits of multithreading, here we increment 1 from 0 to 100000000000000, using serial and parallel methods, and get the time they take to execute the code for comparison.

Public class TestDemo16 {public static void func1 () throws InterruptedException {long big = System.currentTimeMillis (); / / Serial execution Thread t = new Thread (()-> {long a = 0; for (long I = 0 long I {long b = 0; for (long I = 0 th I)

< 10_0000_0000 / 2;i++){ b++; } }); t1.start(); Thread t2 = new Thread(()->

{long c = 0; for (long I = 0 catch I {while (true) {System.out.println ("hello thread1"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () }, "thread1"); Thread T2 = new Thread (()-> {while (true) {System.out.println ("hello thread2"); try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();}, "thread2"); t1.start (); t2.start ();}}

So how can we see the name of the thread that we defined?

Note: when we want to check the thread name, the program must be executing, otherwise we can't find the corresponding thread name.

Determine whether a thread is alive or not

To put it simply, whether the threads we created in the operating system still exist.

The life cycle of Thread t is not exactly the same as that of the corresponding thread in the operating system.

After we define a thread class, there are no threads we created in the operating system before calling the t.start () method. After the execution of the run () method in the thread class, the thread we created in the operating system is destroyed! But the thread t object still exists.

All in all, there are no threads we created in the operating system before calling the t.start () method and after executing the run () method.

After calling the t.start () method, and before pointing to the run () method, there is a thread in the operating system that we created to determine whether the thread is a background thread.

If a thread is a background thread, then the thread will not exit the process.

If a thread is a foreground thread, then this thread will affect the exit of the process. Our above code is creating threads, and those threads are foreground threads. If there is a foreground thread T2, even if the execution of the main thread ends now, the thread cannot be exited at this time. The entire thread will not end until the execution of the T1 T2 thread ends.

If there are two threads, T1 ~ T2, both of which are background threads, then if the execution of the mainthread ends now, the whole process ends, and we will force the stop of the T1 ~ ~ T2 thread.

Public class TestDemo18 {public static void main (String [] args) {Thread t = new Thread (()-> {System.out.println ("hello thread");}); t.start (); System.out.println (t.isDaemon ());}} / / because we are creating a foreground thread, we return other common properties of falseThread to create threads

Create a thread: define a thread class, and then start the thread t.start (), where the start () method determines whether the system actually creates the thread.

Interrupt of thread

The interrupt thread can simply be understood as letting the execution of the run () method in the thread end. Another special is the main thread, if you want to interrupt the main thread, then you need to finish executing the mainthread.

Interrupt thread method 1: set a flag bit

Public class TestDemo21 {public static void main (String [] args) {Thread t = new Thread (()-> {while (! Thread.currentThread (). IsInterrupted ()) {System.out.println ("hello thread"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () }); / / start t-thread t.start (); / / interrupt t-thread try {Thread.sleep (5000) after / 5s in main thread;} catch (InterruptedException e) {e.printStackTrace ();} t.interrupt () }}

Run result: when the sout statement in the t thread is executed 5 times, the thread stops.

The above writing is not rigorous enough and is only applicable to that situation, and if it is changed to another code situation, the thread may not be terminated.

In a better way, use the check thread included in the Thread class to see if the thread is broken.

Thread.interrputed () this is a static method Thread.currentThread (). Isinterrupted () where Thread.cerrentThread () can get a reference to the thread.

T.interrupted () is used to interrupt the thread

Public class TestDemo21 {public static void main (String [] args) {Thread t = new Thread (()-> {while (! Thread.currentThread (). IsInterrupted ()) {System.out.println ("hello thread"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () }); / / start t-thread t.start (); / / interrupt t-thread try {Thread.sleep (5000) after / 5s in main thread;} catch (InterruptedException e) {e.printStackTrace ();} t.interrupt () }}

When we interrupt the thread above to determine the flag bit, we use the third method. The first method is used when setting flag bits.

In our daily development, Thread.currentThread (). IsInterrupted () is often used to determine the flag bit and whether the thread has been interrupted.

There is another way to determine the flag bit, but it is a static method that can only determine if there is only one thread in a class, which is the Thread.isinterrupted () method.

The method Thread.currentThread (). Isinterrupted () determines a normal member of Thread, and each instance has a flag bit.

In the future, we will use the Thread.currentThread (). IsInterrupted () method to determine whether the thread is interrupted (flag bit)

Thread wait

Earlier we also introduced the join () method, which allows a certain order of execution between threads. We know that the scheduling in multithreading is random and uncertain, and the execution of multithreading is arranged by the scheduler, which is random and irregular. In fact, thread waiting is an effective method, which is actually to control the order in which threads execute.

Public class TestDemo22 {public static void main (String [] args) throws InterruptedException {Thread t = new Thread (()-> {for (int I = 0 System.out.println ("hello thread"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();}); t.start (); t.join () / / when the main thread calls the t.join () method, the main thread is in a blocking state. When the t thread is finished, wake up the mainthread to execute the post-order code System.out.println ("hello main");}}

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report