Analysis of advanced technology in Java multi-thread programming

Source: Internet
Author: User

Thread group

Threads are created individually, but they can be classified into thread groups for debugging and monitoring. A thread can be associated with a thread group only when it is created. In a program that uses a large number of threads, it may be helpful to use a thread group to organize threads. They can be viewed as directories and file structures on computers.

Send messages between threads

When a thread needs to wait for a condition before continuing execution, only the synchronized keyword is not enough. Although the synchronized keyword prevents concurrent update of an object, it does not implement inter-thread mail. The Object class provides three functions: wait (), Policy (), and policyall (). Take the global climate prediction program as an example. These programs divide the earth into many units. In each cycle, the calculation of each unit is isolated until these values tend to be stable, and then some data is exchanged between adjacent units. Therefore, in essence, each thread in each loop must wait for all threads to complete their respective tasks before entering the next loop. This model is called blocking synchronization. The following example illustrates this model:

 Shield Synchronization

public class BSync {
  int totalThreads;
  int currentThreads;

  public BSync(int x) {
   totalThreads = x;
   currentThreads = 0;
  }

  public synchronized void waitForAll() {
   currentThreads++;
   if(currentThreads < totalThreads) {
    try {
     wait();
    } catch (Exception e) {}
   }
   else {
    currentThreads = 0;
    notifyAll();
   }
  }
}

When wait () is called for a thread, the thread is blocked only until the other thread calls y () or yyall () for the same object. Therefore, in the previous example, different threads call the waitForAll () function after completing their work, and the last thread triggers the policyall () function, this function will release all threads. The third function notify y () only one waiting thread. This function is useful when you restrict access to resources that can only be used by one thread at a time. However, it is impossible to predict which thread will receive this notification, because it depends on the Java Virtual Machine (JVM) scheduling algorithm.

  Give CPU to another thread

When a thread abandons a rare resource (such as a database connection or network port), it may call the yield () function to temporarily lower its priority so that other threads can run.

Daemon thread

There are two types of threads: User thread and daemon thread. User threads are the threads that complete useful work. Daemon threads are threads that only provide auxiliary functions. The Thread class provides the setDaemon () function. The Java program will run to all user threads to terminate, and then it will destroy all the daemon threads. In the Java Virtual Machine (JVM), the program can continue to run even if another user thread is still running after the main end.

 Avoid unrecommended Methods

We do not recommend that you use methods that are retained to support backward compatibility. They may or may not appear in future versions. Java multithreading support has been significantly revised in versions 1.1 and 1.2. The stop (), suspend (), and resume () functions are no longer recommended. These functions may introduce subtle errors in JVM. Although function names may sound attractive, resist the temptation not to use them.

  Debug a threaded Program

In a threaded program, some common and annoying situations may occur: deadlocks, live locks, memory corruption, and resource depletion.

Deadlock

Deadlock may be the most common problem in multi-threaded programs. A deadlock occurs when one thread needs a resource and the other thread holds the lock of the resource. This situation is usually difficult to detect. However, the solution is quite good: Get all resource locks in the same order in all threads. For example, if there are four resources? A, B, C, and D? In addition, A thread may need to obtain the Lock of any of the four resources. Make sure that the lock of A is obtained first before obtaining the Lock of B, and so on. If "thread 1" wants to obtain the locks for B and C, and "thread 2" gets the locks for A, C, and D, this technology may cause blocking, but it will never cause deadlocks on these four locks.

Live lock

A life lock occurs when a thread is busy accepting new tasks and never has the chance to complete any tasks. This thread will eventually exceed the buffer and cause program crash. Imagine a secretary needs to input a letter, but she has been busy answering the phone, so this letter will never be entered. Memory Corruption

If you use the synchronized keyword wisely, you can avoid memory errors.

 Resource Depletion

Some system resources are limited, such as file descriptors. Multi-threaded programs may use up resources because every thread may want such a resource. If the number of threads is large, or the number of waiting threads for a resource exceeds the number of available resources, it is best to use the resource pool. The best example is the database connection pool. As long as the thread needs to use a database connection, it will retrieve one from the pool and then return it back to the pool. A resource pool is also called a resource pool.

  Debug a large number of threads

Sometimes it is very difficult to debug a program because a large number of threads are running. In this case, the following class may come in handy:

public class Probe extends Thread {
  public Probe() {}
  public void run() {
   while(true) {
    Thread[] x = new Thread[100];
    Thread.enumerate(x);
    for(int i=0; i<100; i++) {
     Thread t = x[i];
     if(t == null)
      break;
     else
      System.out.println(t.getName() + "" + t.getPriority()+ "" + t.isAlive() + "" + t.isDaemon());
    }
   }
  }
}

Restrict thread priority and Scheduling

The Java thread model involves the thread priority that can be dynamically changed. Essentially, the priority of a thread is a number ranging from 1 to 10. The larger the number, the more urgent the task is. The JVM standard calls a thread with a higher priority before calling a thread with a lower priority. However, the processing of threads with the same priority is random. How to handle these threads depends on the operating system policy at the grassroots level. In some cases, threads with the same priority run at a time. In other cases, the threads run until the end. Keep in mind that Java supports 10 priorities, and the base-level operating system may have a much lower priority, which may cause some confusion. Therefore, priority can only be used as a rough tool. The final control can be done by wise using the yield () function. Generally, do not rely on the thread priority to control the thread status.

Summary

This article describes how to use a thread in a Java program. A more important issue like whether to use a thread depends on the application at hand. One way to determine whether to use multithreading in an application is to estimate the amount of code that can be run in parallel. Remember the following points:

Multithreading does not increase the CPU capability. However, if the local thread of JVM is used for implementation, different threads can run simultaneously on different processors (in multiple CPU machines), so that multiple CPU machines can be fully utilized.

If applications are computing-intensive and restricted by CPU functions, only multiple CPU machines can benefit from more threads.

Multithreading is usually advantageous when the application must wait for slow resources (such as network connections or database connections), or when the application is non-interactive.

Internet-based software must be multi-threaded; otherwise, the user will feel the application is slow to reflect. For example, multithreading can make programming easier when developing a server that supports a large number of clients. In this case, each thread can serve different customers or customer groups, thus reducing the response time. Some programmers may have used threads in C and other languages, and there is no language support for threads in those languages. These programmers may usually lose confidence in the thread.

Related Article

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.