Java Line Program Control system

Source: Internet
Author: User

One, the line program control system

Thread-related operations are defined in the thread class, but you can get information about the thread execution environment at run time. For example, see how many processors are available (this is OK?). ):

Runtime.getruntime (). Availableprocessors ();

Threads also provide methods for easy control of threads. 22222

1. Thread Sleep

The static method Thread.Sleep (long Millis) forces the executing thread to pause into sleep and into a blocking state. After the sleep is over, the thread transitions to a ready state.

/* The custom Sleep time unit is in milliseconds */ /* exception handling is required */ Try {    catch(interruptedexception e) {        e.printstacktrace ();}

It is worth emphasizing that:

    • Thread sleep is the best way to help all other threads get the chance to run;
    • The thread sleep expires automatically and returns to the ready state, not the running state. Then, the time specified in the sleep () parameter is the shortest time to stop running, and it cannot be guaranteed to start after waking from sleep;
    • Sleep () is a static method that only controls the currently running thread;

2. Thread Concession

The yield () method causes the current thread to give up CPU possession, similar to sleep (), but does not allow the time to be set. and yield () puts the thread into a ready state, which makes it more advantageous for other threads with the same priority to get run opportunities. In practice, there is no guarantee that yield () can achieve concessions, such as a concession thread being selected by the JVM.

The yield () method does not release the lock flag. In fact, the yield () method corresponds to the following: detects if the thread that currently has the same priority is in the ready state. If so, give the CPU ownership to this thread, and if not, continue running the original thread. So what yield () is trying to do is to give the running opportunity to other threads of the same rank, and not to get the lower level threads.

3. Thread Join

Calls the join () method of another thread in the current thread, and the current thread goes into a blocking state. The blocked thread returns to the ready state until another thread finishes running.

Join () is a non-static method of the thread class, as well as an overloaded version with a time-out limit, such as T.join (5000), which allows the thread to wait for 5000ms, and after the timeout, the blocked process enters the ready state.

4. Thread Priority

When the app starts, the main thread is the first user thread that is created, and the program can create multiple user threads and daemon threads.

When all the user threads have finished executing, the JVM terminates the process.

To set the priority of a thread:

/* priority is 1~10 */ Thread t=new  MyThread (); /* Set Thread Priority */ t.setpriority (8); /* Get Thread Priority */ t.getpriority (); T.start (); // It's just that higher-priority threads have more chances to run, and there's no guarantee that the lower-priority threads will run before. 

The priority level of the daemon thread is the lowest, which is used to provide services to other objects and threads in the system, such as automatically reclaiming threads from resources in the JVM.

The way to set a user thread as a daemon is to call the thread-to-line Setdaemon () method before the Threads object is created.

5. Thread Group Management

Threadgroup class

Once a thread is joined to a thread group, the thread persists in that thread group until it dies and cannot change the group to which the thread belongs.

Second, thread synchronization

The significance of thread scheduling is that the JVM performs system-level coordination on multiple threads running to avoid multiple threads competing for limited resources and causing the application to crash.

Synchronization is a mechanism that prevents data inconsistencies that result from access to shared resources. That is, when multiple threads access the same shared resource, you need to ensure that the resource is accessed by only one thread over a period of time.

1. Lock mechanism

The keyword synchronized is a code block or method that locks to achieve synchronization. The thread locks on the critical resource, denying access to other threads until the line is threads unlocked.

In fact, any object has a monitor for locking and unlocking, and when the code block or method declared by synchronized is executed, it means that the current thread has successfully acquired the lock on the object monitor. Locks acquired by the current thread are automatically freed when normal execution is completed or an exception exits

A thread can add multiple locks on an object, and the JVM guarantees that the value of the variable before the lock is acquired and after the lock is released is synchronized with the content in main memory.

1. Synchronization method

Use the Synchronized declaration method.

When accessing an object's synchronization method, this object is locked! Therefore, when the synchronization method of an object is executed by a thread, other threads cannot access any of the object's synchronization methods, but other non-synchronous methods can be called.

When you invoke the static synchronization method of an object, it locks the class object that corresponds to the object in which the synchronization method resides. Therefore, other threads cannot call other static synchronization methods of the class, but you can call a non-static synchronization method.

2. Synchronizing code blocks

Use the synchronized declaration to synchronize a block of code, lock the object to which it resides, or a specific object, and also the object as an executable flag to achieve the synchronization effect.

3, synchronous method is a coarse-grained concurrency control, only one thread at a time can execute the synchronization method. Synchronous code blocks are fine-grained concurrency control that only synchronizes the code in the block, and code outside the block can be accessed concurrently by other threads.

Use synchronized to note:

    • Synchronized keywords cannot inherit;
    • Synchronized cannot be used when defining interface methods;
    • The construction method cannot use the Synchronized keyword, but it can be synchronized using the synchronized code block;

Third, thread collaboration

There is a collaborative relationship between threads to accomplish a task. such as the producer-consumer model.

Multithreading can interact and communicate by accessing and modifying the same resource (object), just to be aware of the security of thread access. When the thread requires insufficient resources, it enters the wait state, while the other thread is responsible for notifying the waiting thread at the appropriate time.

The wait-notification mechanism is the basic mechanism for completing synchronization between threads.

1. Wait and notify primitive language

2. Producer-Consumer issues

Iv. thread Pool

V. New features of thread synchronization control

Java Line Program Control system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.