IBM Java multi-thread - the thread of life 2


Life thread   1. Create a thread 2. The thread does not create a thread start and the same 3 end of the thread 4. Add thread 5. scheduling 6. Sleep 7. daemon thread 8. Example: factoring large tasks with a plurality of threads 9. Summary
  
  
  
  
  
  
  
  
 

Create a thread Page 1 (9 pages)


Creating a thread in a Java program There are several ways. Each Java program contains at least one thread: the primary thread. Other threads are by Threadconstructor or an instance of the class inherits Threadthe class to create.

Java thread can be directly instantiated Threadobjects or instances of inherited Threadobjects to create other threads. In the thread the basis of examples (which we calculate as many primes within ten seconds), we have by instantiating CalculatePrimesthe object type (it inherits Thread), I created a thread.

When we discuss the Java program threads may refer to two related entities: the actual thread or threads of the work done on behalf of Threadthe object. Running thread is usually created by the operating system; Threadobjects are created by the Java VM, as a way to control the associated thread.

Create a thread and start the thread is not the same Page 2 (9 pages)

In a new thread to thread Threadcalls the object start()before the method, this new thread has not really started. ThreadThe object before it really started threads has existed, and still exists after its thread exits. This allows you to control or obtain information about the thread has been created, even if the thread has not started or has been completed.

Usually by the constructor start()is not a good idea to start a thread. In doing so, the object will be exposed to the partially constructed new thread. If the object has a thread, then it should provide a start-up that thread start()or init()method, rather than start it from the constructor. (See Resources to obtain articles provide links to more detailed description of this concept.)

The end of the thread Page 3 (total 9)

Thread will end in one of three ways:

  • Thread reaches its run()end approaches.

  • Thread throws an uncaught Exceptionor Error.

  • Another thread calls a deprecated stop()method. Abandoned refers to these methods still exist, but you should not use them in new code, and should try to remove them from the existing code.

When all threads in Java programs are completed, the program exits.

Join thread Page 4 (total 9)

Thread API contains methods to wait for another thread to complete: join()method. When calling Thread.join(), the calling thread will block until the target thread is completed.

Thread.join()Often used by programs that use threads to be a big problem into a number of small problems, small problems each is assigned a thread. Examples at the end of this chapter to create ten threads, start them, then Thread.join()wait for them to complete.

Dispatch Page 5 (total 9)


Except when to use Thread.join()and Object.wait()external, thread scheduling and execution timing is uncertain. If two threads to run simultaneously, and do not wait, you must assume that between any two instructions, other threads can run and modify program variables. If the thread variables to be accessed by other threads can be seen, such as data from the static fields (global variable) referenced directly or indirectly, you must use synchronization to ensure data consistency.

In the following simple example, we will create and start two threads, each thread to print two lines System.out:


public class TwoThreads {

    public static class Thread1 extends Thread {
        public void run() {
            System.out.println("A");
            System.out.println("B");
        }
    }

    public static class Thread2 extends Thread {
        public void run() {
            System.out.println("1");
            System.out.println("2");
        }
    }

    public static void main(String[] args) {
        new Thread1().start();
        new Thread2().start();
    }
}
          

We do not know in what order to perform these lines, just know that "1", "2" before printing, as well as "A" you printed "B". Output may be any of the following results:

  • 1 2 A B
  • 1 A 2 B
  • 1 A B 2
  • A 1 2 B
  • A 1 B 2
  • A B 1 2

Not only the results may be different between different machines, and multiple runs of the same program might generate different results on the same machine. Never assume a thread will perform some action before another thread, unless you have used synchronized to force a particular order of execution.

Dormancy Page 6 (9 pages)


Thread API includes a sleep()method, it will make the current thread into a wait state until after a specified period of time or until another thread of the current thread Threadobject to call up Thread.interrupt(), thereby interrupting the thread. After over a specified period of time, turn the thread becomes runnable, and return to the scheduler queue of runnable threads.

If a thread is to Thread.interrupt()call interrupted, then the thread will throw dormant InterruptedException, so the thread will know that it is a wake-up interrupt, you do not have to see whether the timer has expired.

Thread.yield()Methods like Thread.sleep()the same, but it does not cause sleep, but only for a moment suspend the current thread, so that other threads can run. In most implementations, when a higher priority thread calls Thread.yield(), the lower priority thread will not run.

CalculatePrimesThe example uses a background thread computing primes, then sleep ten seconds. When the timer expires, it will set a flag, it said it had been ten seconds.

Daemon threads Page 7 (total 9)


We mentioned that when all the threads Java programs are completed, the program exits, but this is not entirely correct. Hidden system threads, such as garbage collection thread and other threads created by the JVM what will happen? We have no way to stop these threads. If those threads are running, how to exit the Java program do?

The system thread called daemon threads. Java program after it is in fact all non-daemon threads complete withdrawal.

Any thread can become a daemon thread. By calling Thread.setDaemon()to indicate a thread is a daemon thread method. You might want to use as a background daemon threads to create a thread in the program, such as a timer thread or other delay the event thread, only when other non-daemon thread is running, these threads to be useful.

Example: break down large tasks with multiple threads Page 8 (total 9)


In this example, TenThreadsit shows a ten-threaded program creates, each thread execute part of the job. The program waits for all threads completed, and then collect the results.


/**
 * Creates ten threads to search for the maximum value of a large matrix.
 * Each thread searches one portion of the matrix.
 */
public class TenThreads {

    private static class WorkerThread extends Thread {
        int max = Integer.MIN_VALUE;
        int[] ourArray;

        public WorkerThread(int[] ourArray) {
            this.ourArray = ourArray;
        }

        // Find the maximum value in our particular piece of the array
        public void run() {
            for (int i = 0; i < ourArray.length; i++) 
                max = Math.max(max, ourArray[i]);                
        }

        public int getMax() {
            return max;
        }
    }

    public static void main(String[] args) {
        WorkerThread[] threads = new WorkerThread[10];
        int[][] bigMatrix = getBigHairyMatrix();
        int max = Integer.MIN_VALUE;
        
        // Give each thread a slice of the matrix to work with
        for (int i=0; i < 10; i++) {
            threads[i] = new WorkerThread(bigMatrix[i]);
            threads[i].start();
        }

        // Wait for each thread to finish
        try {
            for (int i=0; i < 10; i++) {
                threads[i].join();
                max = Math.max(max, threads[i].getMax());
            }
        }
        catch (InterruptedException e) {
            // fall through
        }

        System.out.println("Maximum value was " + max);
    }
}


小结
第 9 页(共9 页)

就象程序一样,线程有生命周期:它们启动、执行,然后完成。一个程序或进程也许包含多个线程,而这些线程看来互相单独地执行。

线程是通过实例化 Thread 对象或实例化继承 Thread 的对象来创建的,但在对新的 Thread 对象调用 start() 方法之前,这个线程并没有开始执行。当线程运行到其 run() 方法的末尾或抛出未经处理的异常时,它们就结束了。

sleep() 方法可以用于等待一段特定时间;而 join() 方法可能用于等到另一个线程完成。





Reproduced in: https: //www.cnblogs.com/licheng/archive/2008/09/23/1296804.html

Guess you like

Origin blog.csdn.net/weixin_33712987/article/details/92631590