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 create a Java thread object

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge of "how to create Java thread objects". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

By default, both the main thread and the garbage collection thread are created by the system, but we need to complete our own function-create our own thread object

Java makes threads object-oriented, and the resulting class is Thread. The method to perform tasks within the Thread class is called run ().

Note: if you want to use run as the task area, you must let it be called automatically. We start the thread by executing the start () method, and then realize the automatic call of the run method.

Name of the main thread: name of the main child thread: starting with Thread-0

/ / create your own thread object

/ / Analysis: since the actual function Thread class we implement is indeterminate, there is no way to put our function into the run method of Thread. If we want to implement our own function, we can write a subclass of the Thread class, override the run method, and implement our function. Run is our task area.

There are two ways to implement multithreading:

The first way: implement the function by creating a Thread subclass-the thread is bound to the task, so it is not convenient to operate.

The second kind: separate the task from the thread, which thread needs to work, give the task to whom, easy to operate.

When the thread is separated from the task

Here, there is a run inside the Thread by default, and a run is passed in through the ticket. Why is the incoming run called first?

If the thread is constructed using a separate Runnable running object, the run method of the Runnable object is called; otherwise, the method does nothing and returns.

two。 Thread safety

1. Synchronized keyword:

1. There are two scopes of the synchronized keyword:

1) within an object instance, synchronized aMethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, as long as one thread accesses one of the synchronized methods, other threads cannot access any of the synchronized methods in the object at the same time). At this point, the synchronized methods of different object instances do not interfere with each other. That is, other threads can also access the synchronized method in another object instance of the same kind at the same time

2) is the scope of a class, and synchronized static aStaticMethod {} prevents multiple threads from accessing the synchronized static method in this class at the same time. It works on all object instances of the class.

2. In addition to using the synchronized keyword before the method, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block are mutually exclusive. The usage is: synchronized (this) {/ block /}, whose scope is the current object

3. The synchronized keyword cannot be inherited, that is, the method synchronized f () {} of the base class is not automatically synchronized f () {} in the inherited class, but becomes f () {}. Inheriting a class requires you to explicitly specify one of its methods as a synchronized method.

Ways to achieve thread safety:

1. Use synchronization code blocks (synchronization locks) in your code

Explanation: in a certain task, only one thread is allowed to execute the task at the same time, and even if the other thread grabs the cpu, it cannot enter the current task range. Only when the current thread finishes executing the task, can other threads be qualified to enter.

The composition of synchronization code blocks:

Synchronized (lock (object)) {

Synchronized code

}

Requirements for the object to be locked:

1. Must be an object

two。 Must be guaranteed to be shared by multiple threads

That can act as a lock:

1. An ordinary object.

two。 Reference to the current object-- this

3. Class bytecode file-Note: the bytecode file is too widely used and is generally not recommended.

Features of synchronization code blocks:

1. Can ensure the safety of threads.

two。 Because the judgment processing is carried out every time, the execution efficiency is reduced.

Summary: when to use synchronous code blocks

1. Multiple threads share one data

two。 At least two threads

Compare synchronization code blocks with synchronization functions

The synchronization code block is more flexible to synchronize only the part of the code that needs to be synchronized, while the synchronization function synchronizes all the code within this function.

Since there is as little code in synchronization as possible, it is best to use synchronization blocks

Note: 1. When there are multiple synchronized-decorated code blocks or functions in a class at the same time, to be safe, you must make the objects behind them consistent. Because only the same lock can be safe.

Lock of synchronization function: this

2 static synchronization functions do not create objects when they enter memory, but there are bytecode file objects of the class to which they belong, objects of class type.

So the lock of the static synchronization function is the bytecode file object of the class it belongs to.

Example:

/ / use synchronization code blocks

Public void addMoney (int money) {

Synchronized (Bank.class) {

This.money + = money

System.out.println (this.money)

}

}

/ / use synchronization function

/ / non-static synchronization function

/ / there is a this by default after synchronized

Public synchronized void addMoney (int money) {

This.money + = money

System.out.println (this.money)

}

Wait (): make the current thread wait, put it in a pool (thread container), and lose the ability to grab cpu. Wait for a wake-up call (the lock is equivalent to marking the current thread)

Notify (): wakes the current thread from the waiting state, which is equivalent to taking the thread out of the pool. (any thread under the same lock is awakened)

NotifyAll (): wakes up all threads under the same lock

Deadlock: there are two kinds of situations

1. All threads are waiting

two。 Make nested calls between locks

2.Lock

Compare synchronized and Lock

1.synchronized: a synchronization method that has been used since jdk1.0-called implicit synchronization

Synchronized (lock object) {/ / acquire a lock we will lock can also be called a lock flagship or listener

Synchronized code

} / / release the lock

2.Lock: a synchronization method that starts with jdk1.5-called display synchronization

Principle: Lock itself is an interface, to create objects through its subclasses to do work

The process of use:

First call the lock () method to acquire the lock

A block of code to synchronize

Release the lock using the unlock () method

Scenarios used:

When performing the function of multi-producer and multi-consumer, use Lock, and others use synchronized.

In terms of efficiency, Lock is higher than synchronized

Stop of thread: 3 kinds

1. End the thread with an identity

two。 Call the stop method-because of inherent security problems, it is not recommended.

3. Call the interrupt method-if the target thread waits for a long time (for example, based on a condition variable), you should use the interrupt method to interrupt the wait.

Daemon thread:

Equivalent to background threads. Depends on the foreground thread. Normally, when the foreground thread ends, whether the daemon thread ends or not, it ends immediately.

Typical daemon thread: garbage collection thread

When the program calls the setDaemon method, the parameter is set to true. The current thread becomes the guardian layer.

Note: this method must be called before the start method

Thread0.setDaemon (true)

Thread0.start ()

Join () method:

Principle: once a thread calls the join method, it takes precedence over the main thread. The main thread waits for the current thread to finish execution.

Note: the priority is only higher than that of main threads. It has no effect on other threads.

When the thread starts working, let t0 call the join method so that it takes precedence over the main thread

Note: the join method must be executed after the thread starts working.

T0.start (); try {t0.join ();} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}

Wait (): puts a thread in a waiting state and releases the lock of the object it holds.

Sleep (): puts a running thread to sleep, which is a static method that is called to catch InterruptedException exceptions.

Notify (): wakes up a waiting thread. Note that when this method is called, it does not exactly wake up a waiting thread. Instead, it is up to JVM to determine which thread to wake up, not by priority.

NotityAll (): wake up all threads in a waiting state and note that instead of giving all wake-up threads a lock on an object, let them compete.

That's all for "how to create a Java Thread object". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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