1、继承Thread类,重写该类的run方法
2、实现Runnable接口
或者通过java8的lambda表达式创建或者通过线程池创建:Excutors.newCachedThread
3、通过callable和future来启动线程
代码:
public class c_001 { /** * 继承Thread类,重写该类的run方法 */ static class myThread extends Thread{ public void run(){ System.out.println("线程1"); } } /** * 实现runnable接口 */ static class myRun implements Runnable{ @Override public void run() { System.out.println("线程2"); } } static class myCallable implements Callable<Integer>{ @Override public Integer call() throws Exception { int i=0; for(;i<100;i++){ System.out.println(Thread.currentThread().getName()+" "+i); } System.out.println("线程4"); return i; } } public static void main(String[] args) { //启动线程1 new myThread().start(); //启动线程2 new Thread(new myRun()).start(); //启动线程3 new Thread(()->{ System.out.println("线程3"); }).start(); //启动线程4 myCallable c = new myCallable(); FutureTask<Integer> f = new FutureTask<>(c); new Thread(f,"线程4-").start(); try { System.out.println("线程4的返回值="+f.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }