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}}