Method 1: Inherit the Thread class and override the run method
public class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()+"i am is thread!!!!"); } }
Method 2: Implement the Runnable interface and implement the run method
public class MyRunnable implements Runnable{ @Override public void run() { try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace (); } System.out.println(Thread.currentThread().getName()+"i am myrunnable!!!"); } }
Method 3: Implemented by thread pool
public class MyCallable implements Callable<String> { @Override public String call() throws Exception { String str = Thread.currentThread().getName()+":hello world!!"; return str; } }
test
import org.junit.Test; import com.entity.MyCallable; import com.entity.MyRunnable; import com.entity.MyThread; public class ThreadDemo { @Test public void runnableTest() { Thread thread = new Thread(new MyRunnable()); thread.start(); } @Test public void threadTest() { Thread thread = new MyThread(); thread.start(); } @Test public void callableTest() throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new MyRunnable()); Future<String> future = executorService.submit(new MyCallable()); System.out.println(future.get()); } }
Summarize:
***The advantages of implementing the Runnable interface over inheriting the Thread class:
1): Suitable for multiple threads of the same program code to process the same resource
2): The limitation of single inheritance in java can be avoided
3): Increase the robustness of the program, the code can be shared by multiple threads, the code and data are independent
***Use the start method when starting a thread. You cannot directly call the Run method. There is no difference between calling the Run method directly and the method of ordinary classes.
**The difference between Runnable and Callable
difference:
- The biggest difference between the two is that the task thread that implements the Callable interface can return the execution result; the task thread that implements the Runnable interface cannot return the result;
- The call() method of the Callable interface allows exceptions to be thrown; while the exceptions of the run() method of the Runnable interface can only be digested internally, and cannot continue to be thrown;
important point:
- The Callable interface supports returning the execution result. In this case, the FutureTask.get() method needs to be called. This method will block the main thread until the 'future' result is obtained; when this method is not called, the main thread will not block!