Two ways to create threads in Java

Source: Internet
Author: User

Way
    • Inherit the thread class
    • Implementing the Runnable Method
Instance

#继承Thread类

 Public classThreadTest2extendsThread {Private intthreadcnt = 10; @Override Public voidrun () { while(true) {            if(threadcnt > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Number of remaining" +threadcnt); Threadcnt--; Try{Thread.Sleep (30); } Catch(interruptedexception e) {e.printstacktrace (); }            } Else {                 Break; }        }    }     Public Static voidMain (string[] args) {NewThreadTest2 (). Start (); NewThreadTest2 (). Start (); }}

Perform

Thread-1 Number of remaining 10Thread-0 remaining Number 10Thread-0 remaining number 9Thread-1 remaining number 9Thread-0 remaining number 8Thread-1 remaining number 8Thread-0 remaining number 7Thread-1 remaining number 7Thread-1 remaining Number 6Thread-0 remaining Number 6Thread-1 remaining number 5Thread-0 remaining number 5Thread-1 remaining number 4Thread-0 remaining number 4Thread-1 remaining number 3Thread-0 remaining number 3Thread-0 remaining number 2Thread-1 remaining number 2Thread-0 remaining number 1Thread-1 remaining number 1

#实现Runnable方法

 Public classRunnalbleTest2ImplementsRunnable {Private intthreadcnt = 10; @Override Public voidrun () { while(true) {            if(threadcnt > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Number of remaining" +threadcnt); Threadcnt--; Try{Thread.Sleep (30); } Catch(interruptedexception e) {e.printstacktrace (); }            } Else {                 Break; }        }    }     Public Static voidMain (string[] args) {RunnalbleTest2 runnalbleTest2=NewRunnalbleTest2 (); NewThread (RunnalbleTest2). Start (); NewThread (RunnalbleTest2). Start (); NewThread (RunnalbleTest2). Start (); NewThread (RunnalbleTest2). Start (); }}

Perform

Thread-0 remaining number ofthread-1 remaining number ofthread-2 remaining number 8thread-3 remaining number 7thread-1 remaining number 6 Thread-3 remaining number 5thread-2 remaining number 6thread-0 remaining number 6thread-1 remaining number 2thread-0 remaining number 2 Thread-2 remaining number 2Thread-3 remaining 2

It can be seen that although there are 2 threads in the instance, the threadcnt of the operation is one, which realizes the resource sharing.

Comparison

The way to implement interfaces is more flexible than inheriting classes, and can reduce the coupling between programs, interface-oriented programming is also the core of design mode 6 principles

The start () method differs from the run () method

Several states related to threads

New state: When a Thread object is created with the new keyword and the thread class (or its subclasses), the thread object is in the new state. It keeps this state until the program start () this thread.

Ready state: When the thread object invokes the start () method, the thread enters the ready state. The ready state thread is in the ready queue, waiting for the thread scheduler in the JVM to dispatch.

Running state: If the ready state thread gets to the CPU resource , it can execute run (), and the thread is in the running state. A running thread is the most complex and can become a blocking state, a ready state, and a dead state.

Difference

Only the start () method is called to show the multi-threading feature, and the code in the Run () method of the different threads executes alternately. If you just call the run () method, then the code is executed synchronously , and you must wait for the code in the Run () method of one thread to execute after all of it has been executed, and the other thread can execute the code inside its run () method. Test as follows

 PackageCom.jihite.helloworld.thread; Public classTestnostart { Public Static voidMain (string[] args)throwsinterruptedexception {Thread T1=NewThread () {@Override Public voidrun () {Pong (1); Try{Thread.Sleep (7000); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        }; Thread T2=NewThread () {@Override Public voidrun () {Pong (2); Try{Thread.Sleep (7000); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        };        T1.start (); T2.start ();//T1.run ();//T2.run ();System.out.println ("Ping~~~~"); }    Static voidPonginti) {System.out.println ("Pong~" +i); }}
Reference

Java multithreaded Programming

Summary of 40 Java multithreading issues

Two ways to create threads in Java

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.