IBM Java multithreading - 1. thread basis

What's in this tutorial? Page 1 (of 3)

This tutorial explores the basics of the thread - the thread of what, why and how to start a thread useful for writing simple programs using threads.

We will also study more complex, the basic building blocks of the application using threads - how to exchange data between threads, threads, and how to control how threads communicate with each other.

Should I take this tutorial? Page 2 (of 3)

This tutorial is for Java has extensive knowledge of the language, but not many multithreading or concurrency experienced Java programmers.

After reading this tutorial, you should be able to write a simple program using threads. You should also read and understand the program simplest way to use threads.


About the Author
Page 3 (of 3)

Brian Goetz is developerWorks the Java technology zone is a regular columnist he has been a professional software developer for the past 15 years. He is Quiotix chief adviser, which is a California Los Altos (Los Altos) software development and consulting company.

In the popular industry publication you can see Brian 's published and upcoming articles .

By [email protected] contact Brian.

Thread basis

-thread basis
 1. What is a thread?
 2. Every Java program uses threads
 3. Why use threads?
 4. more responsive the UI
 5. The use of multi-processor systems
 6. simplified modeling
 7. asynchronous or background processing
 8. A simple, but sometimes risky
 9. not done head
 10. Example: Use one thread for clocking, and a thread to do the work of
 11. Summary

What is a thread?
Page 1 (total 11)


Almost every operating system support for the process of the notion - the process in a way that is isolated from one another, stand-alone program.

Threading is to allow multiple activities to coexist in a process tool. Most modern operating systems support threads, and the concept of threads in various forms has existed for many years. Java was the first to explicitly include threads in the language itself in mainstream programming language, it does not have to be seen as the thread of the underlying operating system tools.

Threads are sometimes called lightweight processes . Just like processes, threads are independent in the program, concurrent paths of execution, each thread has its own stack, program counter and its own local variables. However, compared with the process of separating, degree of isolation between the threads in the process to be small. They shared memory, file handles, and other processes of each state should have.

Process can support multiple threads, which appear simultaneously executed, it will not sync between each other. Multiple threads in a process share the same memory address space, which means that they can access the same variables and objects, and they heap allocated objects from the same. Although it makes sharing information between threads easier, but you must be careful to ensure that they do not interfere with other threads in the same process.

Java thread API tools and deceptively simple. However, the effective use of threads to write complex programs is not very easy. Because there are multiple threads in the same memory space and share the same variable co-exist, so you must be careful to ensure that your thread will not interfere with each other.

Every Java program uses threads Page 2 (Total 11)


Every Java program has at least one thread - the main thread. When a Java program starts, JVM creates the main thread, and the thread procedure calls in the main()method.

JVM also creates other threads, you usually do not see them - for example, with garbage collection, termination and other objects JVM housekeeping tasks associated thread. Other tools also create threads, such as the AWT (Abstract Window Toolkit (Abstract Windowing Toolkit)) or Swing UI toolkit, servlet containers, application servers, and RMI (remote method invocation (Remote Method Invocation)).

Why use threads? Page 3 (total 11)


In a Java program uses threads for many reasons. If you're using Swing, servlet, RMI or Enterprise JavaBeans (EJB) technology, you might not realize that you are already using a thread.

Some reasons for using threads is that they can help:

  • The UI more responsive
  • Take advantage of multiprocessor systems
  • Simplified modeling
  • Asynchronous or background processing

More responsive UI Page 4 (total 11)

Event-driven UI toolkits (such as AWT and Swing) have an event thread that handles UI events, such as keystrokes or mouse clicks.

AWT and Swing program to event listeners to UI objects. When a specific event (such as a button being clicked) occurs, the listener will be notified. Event listeners are called in AWT event thread.

If the event listener to be executed prolonged tasks, such as checking a large document spelling, event thread will be busy running the spelling checker, so before the completion of the event listener, you can not handle the extra UI events. This would make the program appear to freeze, so users know what to do.

To avoid stalling the UI, the event listener should be long tasks to another thread, so AWT thread can continue processing UI events during the execution of the task (including the elimination of the long-running task is executed request).

Take advantage of multiprocessor systems Page 5 (total 11)

Multi-processor (MP) system more than they used to be. Before they were found only in large data centers and scientific computing facilities. Now many low-end server systems - and even some desktop systems - have multiple processors.

Modern operating systems, including Linux, Solaris and Windows NT / 2000, can take advantage of multiple processors and schedule threads to execute on any available processor.

The basic unit of scheduling is generally the thread; if a program has only one active thread, it can only run on a single processor. If a program has multiple active threads, it can schedule multiple threads simultaneously. In a well-designed program, a program using multiple threads can improve throughput and performance.

Simplified modeling Page 6 (Total 11)


In some cases, the use of threads can make the program easier to write and maintain. Consider a simulation application, which you want to simulate the interaction between multiple entities. Giving each entity its own thread can make a lot of simulation and modeling applications is greatly simplified.

Another suitable example of a separate thread is to simplify the process of an application has multiple independent event-driven time. For example, an application might have a component that after a certain number of seconds countdown event and update the screen display. Instead of letting a main loop periodically check and update the display time, let a thread does nothing, it has been dormant until after a certain period of time, updates the counter on the screen, which is more simple and less error prone. Thus, the main thread does not need to worry about the timer.

Asynchronous or background processing Page 7 (Total 11)


Server applications get input from remote sources (such as sockets). When reading a socket, if no data currently available, then the SocketInputStream.read()call will block until there is data available so far.

If a single-threaded program to be read from the socket, and the other end of the socket entity does not transmit any data, the program would simply wait forever, and no other processing. Instead, the program can poll the socket to see if there is data available, but usually do not use this approach, because the impact of performance.

However, if you create a thread to read from the socket, then when the thread is waiting for input socket, the main thread can perform other tasks. You can even create multiple threads, so you can simultaneously read multiple sockets. Thus, when there is data available, you will be notified quickly (because the thread is waiting to be awakened), without having to constantly polled to check for available data. Use thread waits socket polling code is also simpler than, less error-prone.

Simple, but sometimes there are risks Page 8 (total 11)


Although Java thread tool very easy to use, but when you create multi-threaded applications, you should try to avoid some of the risks.

When multiple threads access the same data item (such as a static field, can be shared globally accessible instance field or collection of objects), they need to ensure coordinated access to data so that they can see a consistent view of the data, but not each other change would interfere with the other. To achieve this purpose, Java language provides two keywords: synchronizedand volatile. We will study the use and meaning of these keywords later in this tutorial.

When accessing the variable from multiple threads, it is necessary to ensure proper conduct of the synchronized access. For a simple variable, the variable declared as volatilemay be sufficient, but in most cases, require the use of synchronization.

If you are going to use synchronization to protect access to shared variables, you must make sure that in the program for all local variables are accessed using the synchronization.

Do not overdo it Page 9 (Total 11)


While threads can greatly simplify many types of applications, overuse of threads could jeopardize the program's performance and maintainability. Thread consumes resources. Therefore, without sacrificing performance, the number of threads that can be created is limited.

Especially in single-processor system, using multiple threads does not cause major consuming CPU resources that the program run faster.


Example: Using a thread for timing and use another thread to complete work Page 10 (Total 11)


The following example uses two threads, one for counting and one for the actual work. The main thread to calculate prime numbers using a very simple algorithm.

在它启动之前,它创建并启动一个计时器线程,这个线程会休眠十秒钟,然后设置一个主线程要检查的标志。十秒钟之后,主线程将停止。请注意,共享标志被声明成 volatile


/**
 * CalculatePrimes -- calculate as many primes as we can in ten seconds 
 */ 

public class CalculatePrimes extends Thread {

    public static final int MAX_PRIMES = 1000000;
    public static final int TEN_SECONDS = 10000;

    public volatile boolean finished = false;

    public void run() {
        int[] primes = new int[MAX_PRIMES];
        int count = 0;

        for (int i=2; count<MAX_PRIMES; i++) {

            // Check to see if the timer has expired
            if (finished) {
                break;
            }

            boolean prime = true;
            for (int j=0; j<count; j++) {
                if (i % primes[j] == 0) {
                    prime = false;
                    break;
                }
            }

            if (prime) {
                primes[count++] = i;
                System.out.println("Found prime: " + i);
            }
        }
    }

    public static void main(String[] args) {
        CalculatePrimes calculator = new CalculatePrimes();
        calculator.start();
        try {
            Thread.sleep(TEN_SECONDS);
        }
        catch (InterruptedException e) {
            // fall through
        }

        calculator.finished = true;
    }
}

小结 第 11 页(共11 页)


Java 语言包含了内置在语言中的功能强大的线程工具。您可以将线程工具用于:

  • 增加 GUI 应用程序的响应速度
  • 利用多处理器系统
  • 当程序有多个独立实体时,简化程序逻辑
  • 在不阻塞整个程序的情况下,执行阻塞 I/O

当使用多个线程时,必须谨慎,遵循在线程之间共享数据的规则,我们将在共享对数据的访问中讨论这些规则。所有这些规则归结为一条基本原则:不要忘了同步


转载于:https://www.cnblogs.com/licheng/archive/2008/09/23/1296800.html

Guess you like

Origin blog.csdn.net/weixin_33938733/article/details/92631570