JAVA single-thread and java multi-thread implementation

Source: Internet
Author: User

JAVA single-thread and java multi-thread implementation

1. java single-thread implementation

Public class SingletonThread {@ SuppressWarnings ("static-access") public static void main (String [] args) {Thread t = Thread. currentThread (); t. setName ("Singleton thread"); System. out. println (t. getName () + "running"); for (int I = 0; I <2000; I ++) {System. out. println ("the thread is sleeping:" + I); try {t. sleep (500);} catch (InterruptedException e) {System. out. println ("thread Error !! ");}}}}


2. java multi-thread implementation

① Inherit the Thread class and override the run Method

Public class ThreadImpl {public static void main (String [] args) {Thread t1 = new ThreadTest ("t1", 200); Thread t2 = new ThreadTest ("t2 ", 100); Thread t3 = new ThreadTest ("t3", 300); t1.start (); t2.start (); t3.start () ;}} class ThreadTest extends Thread {private String name; the private int MS; public ThreadTest (String name, int MS) {this. name = name; this. ms = ms;} public void run () {try {sleep (ms);} catch (InterruptedException e) {System. out. println ("thread running interruption exception");} System. out. println ("the thread named" + name + "starts to sleep" + ms + "millisecond ");}}
Result:

The thread named t2 starts to sleep for 100 milliseconds the thread named t1 starts to sleep for 200 milliseconds the thread named t3 starts to sleep for 300 milliseconds

② Implement the runnable interface and override the run method.

public class RunnableImpl {public static void main(String[] args) {RunnableTest r1=new RunnableTest();    Thread t=new Thread(r1);     t.start();}    }class RunnableTest implements Runnable{    @Overridepublic void run() {// TODO Auto-generated method stub}}




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.