Simple use of JDK threads

Source: Internet
Author: User
Tags ticket

I. How threads are implemented
Way one: Inherit the thread class
A class can implement multi-threaded operations as long as it inherits the thread class and overrides the run () method.

 Public classThreadDemo01 { Public Static voidMain (string[] args) {Thread1 thread1=NewThread1 ("Thread1"); Thread2 thread2=NewThread2 ("Thread2");        System.out.println (Thread1.getname ());        System.out.println (Thread2.getname ()); Thread1.start (); //Start ThreadThread2.start (); }}classThread1extends Thread { PublicThread1 (String name) {Super(name); } @OverridePublic void  Run () { for(inti = 0; I < 10; i++) {System.out.println ("Thread1:" +i); }    }}classThread2extendsThread { PublicThread2 (String name) {Super(name); } @Override Public voidrun () { for(inti = 0; I < 10; i++) {System.out.println ("Thread2:" +i); }    }}

Mode two: Implement Runnable interface
A class can implement multi-threaded operations as long as the Runnable class is implemented and the run () method is overridden.

 Public classThreadDemo03 { Public Static voidMain (string[] args) {Thread thread1=NewThread (NewMyThread1 (), "Thread1"); Thread thread2=NewThread (NewMyThread2 (), "Thread2");        System.out.println (Thread1.getname ());        System.out.println (Thread2.getname ()); Thread1.start (); //Start ThreadThread2.start (); }}classMyThread1ImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println ("MyThread1:" +i); }    }}classMyThread2Implements Runnable {@OverridePublic void Run () { for(inti = 0; I < 100; i++) {System.out.println ("MyThread2:" +i); }    }}

Comparison of two startup modes :

Put the code that we want the thread to execute into the Run method and start the thread with the Start method, which First prepares the system resources for the execution of the thread and then calls the run method ;

Both methods require the thread's Start method to assign the required system resources to the thread, dispatch the thread to run and execute the thread's Run method, use the implementation interface first (avoid single inheritance), and implement the Runnable interface to realize the sharing of resources.

Two, thread of JDK source code analysis

Thread thread1 = new thread (new MyThread1 (), "Thread1");

Thread Construction method source code is as follows:

 public   Thread (String name) {init ( Span style= "color: #0000ff;" >null , null , name, 0 public   Thread () {init ( null , null , "thread-" + nextthreadnum (), 0);}  public   null , Target, "thread-" + nextthreadnum (), 0);}  public   null , Target, name, 0);}  
 private  void   Init (Threadgroup G, Runnable Target, String name,  long   StackSize) {...         Name.tochararray ();   this . Target = target; ....}  
Private Static int Threadinitnumber; Private Static synchronized int Nextthreadnum () {    return threadinitnumber++;}

 Public void run () {    ifnull) {        target.run ();}    }

1) When a thread object is generated, if no name is set for it, then the name of the thread object will be used as follows: Thread-number, the number will be automatically incremented and shared by all thread objects (because it is a static member variable);

2) When using the Inherit thread class to generate the threading object, we need to rewrite the run () method because the thread class's run () method is not doing anything at this time (target==null);

3) When using the implement Runnable interface to generate the thread object, we need to implement the run () method of the Runnable interface and then use the new thread (new MyThread ()) (if MyThread has implemented the Runnable interface) To generate the thread object, the run () method of the thread object invokes the Run method of the Mythread class, so that the run () method we write ourselves executes.

Third, the use of member variables and local variables in the thread

1) If a variable is a member variable, then when multiple threads operate on the member variables of the same object, they affect the member variable (that is, one thread changes the member variable that affects the other).

 Public classThreadDemo04 { Public Static voidMain (string[] args) {hellothread R=NewHellothread (); Thread Thread1=NewThread (R); Thread thread2=NewThread (R);        Thread1.start ();    Thread2.start (); }}classHellothreadImplementsRunnable { int i; //member Variables@Override Public voidrun () { while(true) {System.out.println ("Number:" + This. i++); Try{Thread.Sleep (Long) (Math.random () * 1000)); } Catch(interruptedexception e) {e.printstacktrace (); }            if(10 = = This. I) {                 Break; }        }    }}

The result is:

number:0123456789

2) If a variable is a local variable, then each thread will have a copy of that local variable, and a thread's change to that local variable will not affect other threads.

 Public classThreadDemo05 { Public Static voidMain (string[] args) {worldthread R=NewWorldthread (); Thread Thread1=NewThread (R); Thread thread2=NewThread (R);        Thread1.start ();    Thread2.start (); }}classWorldthreadImplementsRunnable {@Override Public voidrun () {inti = 0;  while(true) {System.out.println ("Number:" + i++); Try{Thread.Sleep (Long) (Math.random () * 1000)); } Catch(interruptedexception e) {e.printstacktrace (); }            if(10 = =i) { Break; }        }    }}

The result is:

number:0011...

Iv. Example of selling tickets

50 tickets, 3 windows to buy, each window equivalent to a thread.

To sell tickets using the inherited thread class:

classMyThread1extendsThread {PrivateInteger num = 50;  PublicMyThread1 (String name) {Super(name); }     Public voidrun () {intCount = 0;  for(inti = 1; I <= 200; i++) {            if(num > 0) {Count++; System.out.println (GetName ()+ "Sell First--->" + num--+ "Ticket"); }} System.err.println (GetName ()+ "sell" + Count + "ticket" ); }}

The GetName () method is derived from the thread class, so it can be obtained directly.

To sell your tickets using the Runnable implementation method:

classMyThread2Implementsrunnable{PrivateInteger num = 50;  Public voidrun () {intCount = 0;  for(inti = 0; I < 200; i++) {            if(num > 0) {Count++; System.out.println (Thread.CurrentThread (). GetName ()+ "Sell First--->" + num--+ "Ticket"); }} System.err.println (Thread.CurrentThread (). GetName ()+ "sell" + Count + "ticket" ); }}

Because the class implements the Runnable interface, the interface does not have a method to get the name of the thread method, so it can only take Thread.CurrentThread (). GetName () The most common way to get the name of the thread being executed.

Comparison of two ways of selling tickets:

Inheritance: Resources can not be shared; sold out 150 tickets, each window 50; Since the thread class inherits, no other classes can be inherited;

Interface mode: resource sharing; sold out 50 tickets; easy to expand later.

Simple use of JDK threads

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.