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 Java threads are defined

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to define Java thread, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Define thread

Define a class A that implements the Runnable interface, and implement the run method in the interface. Finally, instantiate class An as the construction parameter of the Thread class.

/ / define a class A that implements the Runnable interface, and implement the run method public class An implements Runnable {[@ Override] (https://my.oschina.net/u/1162528) public void run () {System.out.println ("opening a county...");}} / / instantiate class AA task = new A (); / / as the construction parameter of the Thread class. Thread t = new Thread (task)

Define a class A that inherits the Thread class, and override the run method of class A

Note: it is actually the run method in the Runnable interface, because the Thread class implements the Runnable interface.

/ / define a class A that inherits the Thread class, and override the run method public class An extends Thread {[@ Override] (https://my.oschina.net/u/1162528) public void run () {System.out.println ();}} Thread t = new Thread () of class A.

Other: through thread pools or methods that implement the Callable interface. Don't make any more introductions for the time being.

The difference between defining threads by implementing the Runnable interface and inheriting Thread classes

The implementation class of the Runnbale interface must override the run () method, while the implementation class of the Thread class has a default implementation of the run method

The implementation class of the Runnbale interface is not a real thread class, it is just a task class that executes the thread.

The Thread class can only rely on the Thread class to execute run methods in a threaded manner

Inheriting the Thread class will cause the limitation of single inheritance

Life cycle of a thread

The life cycle of a thread refers to the creation, startup and completion of the thread.

Six states of java thread

Note: this is about the state of the java thread, not the thread state of the operating system.

The state of the thread is defined by enumeration in the Thread class

Public enum State {NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;}

The state of the thread after New:new Thread () is new.

Runnable: once a thread calls the start () method, the status is Runable regardless of whether it is running or not. Runable status indicates that the thread can run, but it does not mean that the thread must be running. Whether the thread runs or not is determined by the scheduling of the operating system where the virtual machine resides.

BLOCKED: a thread tries to get the Monitor of an internal object (entering a synchronized method or synchronized block) but another thread has preempted it, then this thread is blocked until the other thread releases Monitor and the thread scheduler allows the current thread to get the Monitor, the thread returns to runnable state.

WAITING: when one thread waits for another thread to notify the scheduler of a condition, the thread enters a waiting state.

TIMED_WAITING: similar to waiting, some methods that cause waiting allow you to pass in timeout parameters, such methods cause timed waits, and notifications from other threads or timeouts are returned to runnable state.

TERMINATED: when a thread finishes execution, ends normally or terminates unexpectedly due to an uncaught exception, the thread will enter the terminated state.

Expansion

5 states of threads in the operating system

New

Ready

Running

Blockage

Termination

Thread scheduling

The operating system assigns time slices to each thread and executes only one time slice thread at a time. After each java program starts, jvm will automatically create two threads for us, one is main and the other is GC

Implementation of thread scheduling

Time-sharing scheduling model

Let all threads take turns to gain control of CPU and distribute CPU time fragments evenly for each thread

Preemptive scheduling model

Select the thread with relatively high priority to execute, and if all threads have the same priority, then randomly select a thread to execute the Java virtual machine to use this scheduling model.

Java thread classification

User thread

Also known as non-daemon threads, jvm leaves after all non-daemon threads finish

Daemon thread

Also known as background threads, when all non-background threads in the process end, the background thread also ends.

How to set up background threads

Call the setDaemon () method before the thread starts

Why is the GC thread a daemon thread?

Because when all non-daemon threads are finished, there will be no garbage, so there is no point in the existence of GC threads

Thread safety issues

Thread unsafe conditions occur

There must be two or more threads.

Multiple threads share a resource, and the code that manipulates the resource has multiple sentences.

Solution.

1. Synchronization code block

Decorate the code block with synchronized, as shown below

Public void methodA () {synchronized (this) {/ / doSomething}}

Matters needing attention:

The lock object can be any object.

The lock object must be a resource shared by multiple threads.

The thread that called the sleep method does not release the lock object.

If there is no thread safety problem, do not use synchronization code blocks or synchronization functions, because it will reduce efficiency.

two。 Synchronization function

Using synchronized to decorate this function is called a synchronization function, as shown below.

Public synchronized void methodA () {/ / doSomething}

Matters needing attention:

The lock object of the non-static synchronization function is the this object, and the lock object of the static function is the class file object of the class to which it belongs.

The lock object of the synchronization function is fixed and cannot be changed.

Recommended: synchronize code blocks

The lock object of the synchronization code block can be specified by ourselves, and the lock object of the synchronization function is fixed.

The synchronization code block can specify which scope needs to be synchronized at will, and the synchronization function must synchronize the whole function, and the code is not flexible.

Deadlock

Conditions for the occurrence of deadlocks

There must be two or more threads

These threads share two or more resources

Multiple threads each hold different locks and try to acquire locks that each other already holds.

How to solve

These are all the contents of the article "how Java threads are defined". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more 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.

Share To

Internet Technology

Wechat

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

12
Report