Concurrent programming of thread creation to destruction, common API

  In front of an article on the life cycle of the thread [ concurrent programming thread as much as concept ], in This article deals formal describes how to create, interrupt threads, and how the thread is destroyed. Finally, we will explain some common threads API.

 

Thread Creation

  Java 5 before, there are two ways to implement threads: Extended java.lang.Thread class that implements the interface java.lang.Runnable. Both methods are all directly create a thread, and each new Thread consumes relatively large resources, resulting in poor performance each time new objects; lack of unified management and thread, the new thread may be unlimited, compete with each other, it might take up too many system resources result in death or OOM. At the same time, new Thread thread a lack of more features, such as scheduled execution, periodic execution, the thread is interrupted.

  Java 5 start, JDK provides four thread pool (newFixedThreadPool, newCachedThreadPool, newScheduledThreadPool, newSingleThreadExecutor) to get the thread. The advantage of this is: can reuse existing threads, reducing object creation, the demise of the cost, good performance; and thread pool can effectively control the maximum number of concurrent threads, improve utilization of system resources, while avoiding excessive competition for resources, avoid blocked. Timing may also be implemented by a particular execution thread pool to perform regular, single-threaded, concurrent control.

  Thread creation code implementation

  • Extended java.lang.Thread class
    • A custom class that inherits java.lang.Thread
    • (), The self-defined tasks defined thread on the rewriting Thread run run method
    • Thread object is instantiated custom, and call start () start the thread
// 1. The definition of a class that inherits from Thread class 
public  class ExThread the extends Thread {
     // 2. rewritable RUN () 
    @Override
     public  void RUN () {
        for ( int I = 0; I <100; I ++ ) { 
           the System. Out.println (Thread.currentThread () getName (). + ":" + I); 
       } 
    } 

    public  static  void main (String [] args) {
         // 3. Create Thread subclass object 
        exThread exThread = new new exThread () ;
         // 4. A method for initiating a call start custom thread 
         exThread.start ();
    } 
}

 

  • Implement the interface java.lang.Runnable
    • A custom class that implements Runnable interface
    • Realization run Runnable interface (), the self-defined tasks defined thread on the run method
    • Create an object Runnable implementation class
    • Create Thread object, and the object is to achieve Runnable class as a parameter
    • Call Thread object start () start the custom thread
// 1. a custom class that implements Runnable interface 
public  class ImThread the implements Runnable {
     // 2. implement RUN () 
    @Override
     public  void RUN () {
         for ( int I = 0; I <100; I ++ ) { 
            the System.out .println (Thread.currentThread () getName (). + ":" + I); 
        }   
    } 
   
    public  static  void main (String [] args) {
         // 3. Create a class that implements Runnable objects 
        imThread imThread = new new imThread ();
         // 4. create a Thread object 
        Thread thread =new new the Thread (imThread);
         // 5. The start () call turn thread 
        Thread.start (); 
    } 
}

  

  • newFixedThreadPool

    Creating a fixed number of threads in the thread pool, you can control the maximum number of concurrent threads, excess threads will wait in the queue

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CreateThreadByFixedPool {

    /**
     * Cover Runnable.run()
     */
    private static void run(){
        System.out.println(Thread.currentThread().getName()+" is running...");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            pool.execute(CreateThreadByFixedPool::run);
        }
    }
}

 

  • newCachedThreadPool

    Creating a cache thread pool, thread pool longer than if treatment needs, the flexibility to reclaim idle thread, if not recyclable, the new thread.

    The capacity of the thread pool is infinite, the first task has been completed when the second task, the thread used to perform the first task will be complex, rather than each time a new thread.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CreateThreadByCachedPool {

    public static void main(String[] args) {

        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pool.execute(() -> System.out.println(Thread.currentThread().getName()+" is running..."));
        }
    }
}

 

  • newScheduledThreadPool

    Creating a fixed number of threads in the thread pool to support regular and periodic task execution.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class CreateThreadByScheduledPool {

    public static void main(String[] args) {

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);
//delay 2s excute. pool.schedule(() -> System.out.println(Thread.currentThread().getName()+" delays 2s "), 2, TimeUnit.SECONDS);
//delay 2s and every 3s excute. pool.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName()+" delays 2s every 3s execte"), 2, 3, TimeUnit.SECONDS); } }

 

  • newSingleThreadExecutor

    Creating a single-threaded thread pool, it will only work with a single thread to perform the task to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).

public class CreateThreadBySingleThreadPool {

    public static void main(String[] args) {

        ExecutorService pool = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            pool.execute(() ->{
                System.out.println(String.format("The thread %d (%s) is running...",
                        index,Thread.currentThread().getName()));
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

 

  Thread the thread itself is responsible for the relevant duties and control, Runnable is responsible for logic operations.

  When implementing custom thread it is recommended Runnable interface because it has the following advantages:
  • Java is more than single inheritance implementation, implement the interface in favor of a program to expand
  • Implement Runnable can run multiple threads share () [inheritance Thread class, override the run () can only be used by that thread]
  • Different threads using the same Runnable, do not share resources

 

Thread interrupts

    interrupt () method can be used to request to terminate the thread.
  • When you call a method interrupt thread, the thread interrupt status (boolean flag) will be set.
  • Determine whether the current thread is interrupted, can be used Thread.currentThread.isInterrupt ()
  • Interrupt not forced to terminate a thread, interrupt threads only cause the current thread's attention, by its own decision whether to respond to interrupts. [Some (very important) thread processing continues After an exception, does not care about interruption; but more common situation is: simple thread will be interrupted as a termination request. ]

 

Thread destroyed

    Thread destroyed several scenarios:
  • End of the thread, itself off
  • Abnormal exit
  • Modify isInterrupt by interrupt () () End flag
public static void main(String[] args) throws InterruptedException {
        Thread t  = new Thread(){
            @Override
            public void run() {
                System.out.println("I will start work.");
                while(!isInterrupted()){
                    System.out.println("working....");
                }
                System.out.println("I will exit.");
            }
        };
        t.start();
        TimeUnit.MICROSECONDS.sleep(100);
        System.out.println("System will exit.");
        t.interrupt(); 
    }
  • Using that volatile thread switch off flag (identified as interrupt thread is likely to be erased)] [chapter04.FlagThreadExit
public class FlagThreadExit {

    static class MyTask extends Thread{
        
        private volatile boolean closed = false;
        
        @Override
        public void run() {
            System.out.println("I will start work.");
            while(!closed && !isInterrupted()){
                System.out.println("working....");
            }
            System.out.println("I will exit.");
        }
        
        public void closed(){
            this.closed = true;
            this.interrupt();
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        MyTask task = new MyTask();
        task.start();
        TimeUnit.MICROSECONDS.sleep(100);
        System.out.println("System will exit.");
        task.closed();
    }
}

 

Multi-threaded API

method
return value
effect
 
yield()
static void
Suspend the currently executing thread object, and perform other threads.
Only a priority greater than or equal to the thread priority thread (including the thread) have a chance to be executed
Freeing the CPU, monitor lock will not give up
sleep()
static void
The current thread to sleep, the chance of any other thread has executed
Freeing the CPU, monitor lock will not give up
wait()
void
The current thread to wait
Object methods
interrupt()
void
Interrupt thread
Interruptible method
interrupted()
static boolean
Determine whether the current thread is interrupted
 
isInterrupted()
boolean
Tests whether this thread has been interrupted
 
join()
void
In the thread A, join thread B, thread A enters the BLOCKED state until the end of the life cycle or the thread B BLOCKED A thread state is interrupted another thread
Interruptible method
 
  • After the interrupt method can be interrupted receive interrupt exception InterruptedException.
  • Comparison of yield () and sleep () is
    • Thread class are static methods
    • It will cause the currently running thread to give up CPU
    • yield only to give way to the same or a higher priority thread, sleep gave way to all the threads
    • When the thread executing the sleep method, will be transferred to the blocked state, and after executing the yield method, go to a ready state;
    • sleep method may throw, while the yield is not [sleep is interrupted method, recommended sleep]
  • Comparison of sleep and wait
    • wait and sleep methods can thread into the blocked state
    • wait and sleep are interruptible method
    • Object method makes wait, sleep is a method of Thread
    • wait to be executed in the synchronization code , and need not sleep
    • Synchronization code, sleep monitor will not release the lock, and the wait method releases the monitor lock
    • Obstructive sleep method initiative to withdraw after a brief sleep, while (time not specified) wait method will need to be blocked exit or interrupt will notify other threads

 

Use wait

  • You must use wait and notify methods in sync when the law (wait and notify the premise that must hold ownership of the monitor synchronization method)
  • monitor the synchronization code must be consistent with the object execution wait and notify methods
public class WaitDemo {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(() -> {
            synchronized (WaitDemo.class){
                System.out.println("Enter Thread1...");
                System.out.println(Thread.currentThread().getName()+" is waiting...");
                try {
                    WaitDemo.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread1 is going...");
                System.out.println("Shut down Thread1.");
            }
        });

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        pool.execute(() ->{
            synchronized (WaitDemo.class) {
                System.out.println("Enter Thread2...");
                System.out.println(Thread.currentThread().getName()+" is notifying other thread...");
                WaitDemo.class.notify();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread2 is going...");
                System.out.println("Shut down Thread2.");
            }

        });
    }

}

 

 

supplement

  • The reason deprecated stop () and suspend () of
                stop () is used to terminate a thread, but unsafe; stop () method terminates all is not the end of the current thread, including the run (). The current thread has been terminated, the immediate release of its locked lock. This causes the object in an inconsistent state. [In the transfer process, it may just turn out the money has not yet transferred to another account, the thread is interrupted. Cause the object to be destroyed, data error, other threads will get the wrong object data]
                suspend () is used to block a thread until another thread calls resume (). suspend () will often lead to deadlock. Call to suspend () when the target thread is suspended, but the lock still holds previously obtained. At this point, other threads can access the locked resources. If you call suspend () thread attempts to acquire the same lock, the thread deadlock (suspended thread waiting for recovery, and it hung threads wait for a lock resource)
  • suspend () alternative
                Should put a sign in his class Thread, the thread should be pointed out that active or suspended. If the flag indicates that the thread should hang, they use wait () command it enters the wait state. If the flag indicates that the thread should be restored, then use a notify () to restart the thread.
 
  •  In the actual development, call the start () method to start the thread is no longer recommended. It should reduce the number of tasks to run in parallel from the operating mechanism. If there are a lot of task, to create a separate thread programming the price paid too much for each task. You can use the thread pool to solve this problem.
  •     Thread View tool: JDK comes Jconsole
 

Guess you like

Origin www.cnblogs.com/BlueStarWei/p/11497198.html