Java Threads and multithreading

Source: Internet
Author: User

Java creates threads in two ways:

1. Inheriting thread creating threads

/*** Created by LSF on 16/4/18.*/classNewthreadextendsThread {newthread () {Super();//Creating ThreadsStart ();//Start Thread    }     Public voidrun () {LongStartTime =System.currenttimemillis (); System.out.println ("Child thread ..." +starttime); }}classCurrentthreaddemo { Public Static voidMain (String args[]) {LongStarttime2 =System.currenttimemillis (); System.out.println ("Main thread,,," +starttime2);//Main Thread        NewNewthread (); System.out.println ("Live in the county"); }}

2. Implement

Importcom.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;Importjava.util.Date;/*** Created by LSF on 16/4/18.*/classNewthreadextendsThread {newthread () {thread T=NewThread ( This);//Creating ThreadsT.start ();//Start Thread    }     Public voidrun () {LongStartTime =System.currenttimemillis (); System.out.println ("Child thread ..." +starttime); }}classCurrentthreaddemo { Public Static voidMain (String args[]) {LongStarttime2 =System.currenttimemillis (); System.out.println ("Main thread,,," +starttime2); NewNewthread (); System.out.println ("Main thread");//Main Thread    }}

3. Create multiple threads for the task to execute

classNewthreadextendsThread {String name; Newthread (String threadname) {name=ThreadName; Thread T=NewThread ( This, ThreadName);//Creating ThreadsT.start ();//Start Thread    }     Public voidrun () {LongStartTime =System.currenttimemillis (); System.out.println ("Child thread ..." +name); }}classCurrentthreaddemo { Public Static voidMain (String args[]) {LongStarttime2 =System.currenttimemillis (); System.out.println ("Main thread,,," +starttime2); NewNewthread ("Demo1"); NewNewthread ("Demo2"); NewNewthread ("Demo3"); System.out.println ("Main thread");//Main Thread    }}

4. Thread-Priority setting

/*** Created by LSF on 16/4/22.*/classThreadTestImplementsRunnable {Thread t; intCount = 0; Private volatileBoolean flag =true;  PublicThreadTest (intp) {T=NewThread ( This);    T.setpriority (P); }     Public voidstart () {T.start (); }     Public voidFinish () {flag=false; } @Override Public voidrun () { while(flag) {count++; }    }} Public classthreadpriority { Public Static voidMain (string[] args) {threadtest T1=NewThreadTest (thread.norm_priority-2); ThreadTest T2=NewThreadTest (thread.norm_priority + 2);        T1.start ();        T2.start ();        T1.finish ();        T2.finish (); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        Try{System.out.println ("T1 count:" +t1.count); System.out.println ("T2 Count:" +t2.count);            T1.t.join ();            T2.t.join (); System.out.println ("T1 is alive:" +t1.t.isalive ()); System.out.println ("T2 is alive:" +t1.t.isalive ()); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

5. Thread Synchronization

Thread synchronization is the key to the same time thread in the pipe, the scenario is generally: when a method (CallMe) need to use multi-threaded to execute, you can transform the corresponding method, plus keyword synchronized, so that during the call process, each thread will default into the implicit pipe.

/** * Created by Root on 16-4-15.        */class Callme {synchronized void call (String msg) {System.out.println ("[" +msg);        try {thread.sleep (1000);        } catch (Interruptedexception e) {e.printstacktrace ();    } System.out.println ("]");    }}class Threadcaller implements runnable{String msg;    Callme Target;    Thread T;        Public Threadcaller (Callme targ,string s) {target = Targ;        msg = s;        t = new Thread (this);    T.start ();    } @Override public void Run () {Target.call (msg);        }}class Demo {public static void main (string[] args) {Callme target = new Callme ();        Threadcaller obj1 = new Threadcaller (target, "Hello");        Threadcaller obj2 = new Threadcaller (target, "Synchronized");        Threadcaller obj3 = new Threadcaller (Target, "world");            try {obj1.t.join ();            Obj2.t.join ();        Obj3.t.join ();     } catch (Interruptedexception e) {       System.out.println ("interrupted"); }    }}

  

Java Threads and multithreading

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.