1. Inherit thread, rewrite run ()
public class MyThread extends thread{ @Override public void Run () { System.out.println ("Run Procedure" ); }}
2. Implement Runnable, re-run ()
public class Myrunnable implements Runnable { @Override public void Run () { System.out.println ("Run Process");} }
3. Implement callable, rewrite call ()
Note: The callable interface is a parameterized type, with only one call method, and the call return type is the parameter type.
Public interface callable<v> { /** * Computes a result, or throws an exception if unable to does so. * * @return computed result * @throws Exception if unable to compute a result * /V call () throws E xception;}
Import Java.util.concurrent.callable;public class Mycallale implements callable<integer> { @ Override public Integer call () throws Exception { System.out.println ("Run Process"); return null;} }
Test : Thread A, B, C,a, B are executed at the same time, a, b after execution, execute C
Analysis: Synchronous operation and asynchronous operation, A, b asynchronous, AB and C synchronization (ab blocking, execution after completion of C)
Code: (Implement callable, create a, b thread with Futuretask, call the Get () method to block A, b thread, and finally start thread C)
ImportJava.util.concurrent.callable;importJava.util.concurrent.executionexception;importJava.util.concurrent.futuretask;public classcallabletest {public static void main (string[] args) throwsInterruptedexception, executionexception {//thread A, B run at the same time, thread C runs after a, bcallable<a> A = new callable<a>() {@Override public A call () throwsException {for (int i = 0; i <; i++) {System.out.print ("a" + i);} return new A ();}}; Callable<b> B = new callable<b>() {@Override public B call () throws Exception {for (int i = 0; i < 10; i++) {System.out.print ("B" + i);} return new B ();}}; futuretask<a> Taska = new futuretask<a>(A); futuretask<b> TASKB = new futuretask<b>(B); new thread (Taska). Start (); New thread (TASKB). Start (); if (taska.get () = null && taskb.get ()! = null) {new Thread (new C ()). Start ();}} static Class a{} s Tatic class b{} static class C extends thread{@Override public void Run () {for (int i = 0; i <; i++< c19>) {System.out.print ("C" + i); }}}}
Some ways to create threads in Java, see