Common thread creation methods and basic thread knowledge points summary

Source: Internet
Author: User
Tags thread class

A common thread-creating methods 1-1, Runnable:1-2, Thread:1-3, callable (with Futuretask): 1-4, callable (with thread pool Executorservice and future): 1-5, Anonymous inner class > Inheritance thread 1-6, anonymous inner class > Implementing Runnable Interface II, Thread basics summary 2-1, thread Lifecycle and state transition 2-2, thread scheduling thread priority thread hibernate (Sleep) thread compromise (yield) Thread join (join) thread interrupt (interruppt) 2-3, multithreaded Synchronous Sync code block sync method deadlock 2-4, multithreaded communication 2-5, thread-safe collection

first, several common ways to create threads 1-1, Runnable:

Note : The way to implement the Runnable interface is more commonly used. Write the code for the multithreaded implementation that you want in run (), by passing the Runnable object into the thread construct method, and invoking the Thread object's start () method to open the threads.

1 the same resource as thread,runnabl for multiple threads of the same code (for an intuitive example: When using runnable, you can pass the same Runnable object at each new thread (runnable). Make n thread process one resource at the same time;

2 because Java is a single extends, many implements, it is obvious that the way to write interface is more convenient (note: Thread is actually implemented the Runnable interface)

Implementation Method :

public class Runnabletest {public
    static void Main (string[] args) {
        Runnable myrunnable = new myrunnable ();
        Thread thread = new Thread (myrunnable);
        Thread.Start ();
    }
Class Myrunnable implements runnable{
    @Override public
    void Run () {
        System.out.println ("Hello Runnable" + Thread.CurrentThread (). GetName ());    
    }
1-2, Thread:

Note : Implementing thread requires inheriting the thread class, and the run () and start () methods are provided in thread. The code that is required to implement the multithreaded implementation is used in the run () method, and the thread is opened and executed through the start () method.

Implementation Method :

public class ThreadTest {public
    static void Main (string[] args) {
        mythread mythread = new Mythread ();
        Mythread.start ();
    }
Class Mythread extends thread{
    @Override public
    void Run () {
        System.out.println ("Hello Thread" + Thread.CurrentThread (). GetName ());    
    }
1-3, callable (with Futuretask):

Note : Both runnable and thread cannot avoid the fact that they cannot return results, but using callable+future/futuretask can solve the problem well.

1) callable and runnable are required to implement the corresponding interface, the difference is that the call () method is required for the callable, and the call () method has a return value of type object. It is also noteworthy that callable can throw an exception.

2) Futuretask:futuretask implements Runnablefuture interface, Runnablefuture interface inherits Runnable and future two interfaces. The run () method is implemented in Futuretask, in Run ()
Gets the return value of the call () method that is overwritten by the callable object that is passed in in the constructor method. So the Futuretask object can get the value returned by the callable when it makes a. Gets ().

implementation method (with Futuretask):

public class Callabletest {public
    static void Main (string[] args) {
        callable callable = new mycallable ();
        futuretask<string>  futuretask = new futuretask<string> (callable);
        New Thread (Futuretask). Start ();
        try {
            System.out.println (Futuretask.get ());
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        } catch (Executionexception e) {
            e.printstacktrace ();
}}} Class Mycallable implements callable{
    @Override public
    Object call () throws Exception {
        String str = "Hell o Callable "+ thread.currentthread (). GetName () +" I was acquired. ";
        System.out.println ("Hello callable");
        return str;
    }
}
1-4, callable (with thread pool Executorservice and future):

remark : Callable related to see above

Future: Two methods for obtaining results, including get (), getting (long timeout, timeunit unit), the first of which is blocked until the calculation is complete if the result is not obtained; the latter method can set the blocking time and throw an exception if the result is not obtained.

The thread pool contains 4 kinds: newsinglethreadexecutor Create a single thread pool, newfixedthreadpool create a fixed number of thread pools, newcachedthreadpool create a cacheable thread pool, Newscheduledthreadpool Create a thread pool of infinite size. Two open methods of thread pool submit () differs from Excute () in that the former can accept runnable, callable the latter can only accept runnable and the former can have a return value, and the latter has no return value.

Implementation Method :

public class Callabletest {public
    static void Main (string[] args) {
        Executorservice pool = Executors.newsingleth Readexecutor ();
        Callable callable = new mycallable ();
        future<string> Future = pool.submit (callable);
        try {
            System.out.println (Future.get ());
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        } catch (Executionexception e) {
            e.printstacktrace ();
}}} Class Mycallable implements callable{
    @Override public
    Object call () throws Exception {
        String str = "Hell o Callable "+ thread.currentthread (). GetName () +" I was acquired. ";
        System.out.println ("Hello callable");
        return str;
    }
}
1-5. Anonymous inner class > Inheritance thread

Note: Inherit thread class

public class ThreadTest {public
    static void Main (string[] args) {        
        new Thread () {
            @Override public
            void RU N () {
                System.out.println ("Hello Thread" + thread.currentthread (). GetName ());
        Start ();    
    }
1-6. Anonymous inner class > Implement Runnable interface

Note: implement runnable interface

public class ThreadTest {public
    static void Main (string[] args) {        
        new Thread (new Runnable () {
            @Override 
  public void Run () {
                System.out.println ("Hello Runnable" + thread.currentthread (). GetName ())
        . Start ();
    }
second, the thread basic knowledge points summary 2-1. Thread life cycle and state transition

The entire lifecycle of a thread is 5 states: New, Ready (Runnable), running State (Running), blocking state (block), dead State (terminated).
2-2, the scheduling of the thread Thread Priority

        Thread.setpriority (thread.min_priority);
        Thread.setpriority (thread.max_priority);
        Thread.setpriority (thread.norm_priority);
        Thread.setpriority (10);     
thread Hibernate (sleep)

Thread blocking in milliseconds

Thread.Sleep (Millis);
thread Concession (yield)
Thread.yield ();

The difference with sleep is that the yield method does not block the thread, but simply converts the thread to a ready state, allowing the system scheduler to be dispatched again. Note that this is not a wait or block, nor does it ensure that the running thread is immediately converted to a ready state. In addition, when a thread is yield, only threads with the same priority as the current thread or higher will be given the opportunity to execute. thread Join (join)

When thread a encounters another thread b.join (), a blocks, and then executes after B finishes

public class ThreadTest {public
    static void Main (string[] args) throws interruptedexception {
        thread thread = new Thread (New Runnablea ());
        Thread.Start ();
        for (int i = 0; i < 5; i++) {
            System.out.println ("I am the main thread, running first" + i + "bar");
            try {
                thread.join ();
            } catch (Interruptedexception e) {
                e.printstacktrace ();
            }

}}} Class Runnablea implements Runnable {
    @Override public
    void Run () {
        System.out.println ("I Runnablea started running. ");
        try {
            thread.sleep;
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        }
        System.out.println ("I Runnablea run out now");
    }
Output result:
I am the main thread, running No. 0
i Runnablea started running I Runnablea now run I'm the main thread
, running 1th
I'm the main thread, running 2nd
I am the main thread, running 3rd I am the
main thread, running 4th
thread Interrupt (interruppt)

Interrupt only interrupts blocked threads, throwing interruptedexception exceptions that have no effect on running threads

public class ThreadTest {
    Static object = new Object ();

    public static void Main (string[] args) throws exception{
        Thread thread=  new Mythread ();
        Thread.Start ();
        Thread.Interrupt ();
}
Class Mythread extends thread{public
    void Run () {
        try {
            thread.sleep (5000);
        } catch ( Interruptedexception e) {
            System.out.println ("I was terminated");}
     

Output results

I was terminated.

Note: When using the interrupt, remember to make a deal with the interruptedexception exception that might be thrown. 2-3. Multithreading Synchronization

Note: Code blocks and methods decorated by the Synchronized keyword allow only one thread to access at a time. Synchronizing code blocks

Lock is a lock object that, when the thread executes a synchronized code block, first checks the lock object's flag bit, defaults to 1, at which point the thread executes the synchronized code block and the lock object's flag bit is 0. When other threads execute to this, because the lock object flag bit is 0, there will be blocking, and so on after the current thread finishes executing the synchronized code block, the lock object's flag bit will be placed 1
Note: If the lock object is not static, then each time a lock is new. Only static locks can guarantee the uniqueness of shared variables

Object lock = new Object ();//General write as member variable
synchronized (lock) {
    //Operation shared resource code block
}
Synchronization Method

The lock of the synchronization method is the object that is currently calling the method, and the benefit is that the synchronization method is shared by all threads, and the object of the method is unique to all threads

Modifier  Synchronized Returns the value type method name (parameter 1, parameter 2 ...)
Example: public synchronized void methed () {}
dead Lock

A lock with B lock, B lock with a lock, each other waiting for each other's lock, so that the deadlock

public class ThreadTest {public static void main (string[] args) throws Exception {T
        Hread Threada = new Mythread ("A");
        Thread threadb = new Mythread ("B");
        Threada.start ();
    Threadb.start ();
    Class Mythread extends Thread {static Object Key1 = new Object ();
    static Object Key2 = new Object ();

    String Houseowner;
    Public Mythread (String houseowner) {this.houseowner = Houseowner; public void Run () {if ("A". Equals (Houseowner)) {synchronized (key1) {System.
                Out.println ("I am a I used the 1th lock");
                Synchronized (Key2) {System.out.println ("I am a I used the 2nd lock");
                }} else {synchronized (Key2) {System.out.println ("I am a b i used lock 2nd");
                Synchronized (key1) {System.out.println ("I am a b i used the 1th lock"); }
            }
        }
    }
}

Output results: Visible only 2 statements, and no output of 4 statements, because the back is waiting for each other's lock

I'm a B, I used the number 2nd lock,
I'm a A, I used the 1th lock.
2-4. Multi-threaded communication

Thread communication controls multiple threads to rotate in a certain order by using the lock. Wait (),. Notify ().
Wait (): Causes the current thread to hand over the synchronization lock and begins to wait until another thread calls the Notify () method of the synchronization lock (the Notify () of an object is invoked, and the current thread also needs to have the object lock, so the corresponding execution of the notify in the synchronized code block of the current thread, At the same time, only the synchronization code block in the current thread is finished before the lock can be returned to the waiting thread and awakened, and the following results are observed.

public class ThreadTest {public static Object lock = new Object ();
        public static void Main (string[] args) throws Exception {thread thread = new Mythread ();
        Thread.Start ();
            Synchronized (lock) {System.out.println ("Main thread: Start Wait");
            Lock.wait ();
        System.out.println ("Main thread: I can finally move out"); Class Mythread extends thread {public void run () {try {System.out.println) ("Child Thread: Open Child thread")
            Process ");
            SYSTEM.OUT.PRINTLN ("Child thread: I want to play 5 seconds to wake the main thread");
            Thread.Sleep (5000);
            SYSTEM.OUT.PRINTLN ("Child thread: I play well can wake up the main thread");
                Synchronized (Threadtest.lock) {System.out.println ("Child thread: wake-up main thread");
                ThreadTest.lock.notify ();
                SYSTEM.OUT.PRINTLN ("Child thread: I play 5 Seconds Again");
                Thread.Sleep (5000);
            SYSTEM.OUT.PRINTLN ("Child thread: I play it Again"); The catch (Interruptedexception e) {}}} 

Output results:

Main thread: Start
wait child thread: Open child thread thread
child thread: I want to play 5 seconds to wake the main thread
child threads: I can wake up the main thread.
Child Threads: wake-up main thread
child: I'll play for another 5 seconds
. Child thread: I played the main thread again
: I can finally move.

Note: The thread itself cannot wake itself, as shown in the following figure

public class ThreadTest {public
    static Object lock = new Object ();
    public static void Main (string[] args) throws Exception {
        synchronized (lock) {
            System.out.println ("Main thread: Start wait ");
            Lock.wait ();
            System.out.println ("Main thread: I can finally move out");
            Lock.notify ();
            System.out.println ("Main thread: I can finally move");
        }
        System.out.println ("Main thread: I can finally move");
    }

Output: There is no output behind. (You can't wake yourself up until someone wakes you up)

Main thread: Start wait
2-5, line Cheng Ann Complete Collection

Vector
HashTable
StringBuffer
~ ~~~~~~~~~~~~end~~~~~~~~~~~~~~~~~~~

Closing: A small collation and summary of the thread-related basics, many for merely ~ if there are errors or deficiencies, million hope you can give me ~

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.