There are two ways to create thread threads in Java:
1. By inheriting the thread class, overriding the thread's run () method, placing the logic in which the threads run
2. Instantiate the thread class by implementing the Runnable interface
The first way: Inherit the thread class
PackageCom.yyx.thread;/*** Create threads by inheriting the thread class * Yyx February 4, 2018*/ Public classCreatethreadbyextends { Public Static voidMain (string[] args) {extendthread extendthread=NewExtendthread (); Extendthread.setname ("Thread One");//set the thread nameExtendthread.start (); for(inti = 1; I <= 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); } }}classExtendthreadextendsThread {@Override Public voidrun () { for(inti = 1; I <= 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); } }}
Second way: Implement Runnable interface
PackageCom.yyx.thread;/*** Recommended: Create thread by implementing runnable interface * Yyx February 4, 2018*/ Public classCreatethreadbyinterface { Public Static voidMain (string[] args) {subthread subthread=NewSubthread (); Thread Thread=NewThread (subthread, "thread One")); Thread.Start ();//a thread can only execute once start () for(inti = 1;i <= 100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+":" +i); } }}classSubthreadImplementsRunnable {@Override Public voidrun () { for(inti = 1; I <= 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); } }}
The Third Way: create a thread with a return value using Calable and future
PackageCom.yyx.thread;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.FutureTask;/*** Create a thread with a return value using Calable and future Yyx February 6, 2018*/ Public classCreatethreadbycallableImplementsCallable<integer> { Public Static voidMain (string[] args) {createthreadbycallable createthreadbycallable=Newcreatethreadbycallable (); Futuretask<Integer> task=NewFuturetask<integer>(createthreadbycallable); NewThread (Task, "Threads with a return value")). Start (); Try{System.out.println (Task.get ()); }Catch(Exception e) {e.printstacktrace (); }} @Override PublicInteger Call ()throwsException {Integer total=0; for(inti=1;i<=50;i++) { Total+=i; } returnTotal ; }}
Java Multithreading thread creation