classMyThreadextendsThread{@Overridepublicvoidrun(){//此处为thread执行的任务内容System.out.println(Thread.currentThread().getName());}}publicstaticvoidmain(String[] args){for(int i=0;i<2;i++){Thread t =newThread(newMyThread());
t.start();}}
2. 实现Runnable接口,用新的类创建Thread实例,调用start
classMyThreadimplementsRunnable{@Overridepublicvoidrun(){//此处为thread执行的任务内容System.out.println(Thread.currentThread().getName());}}publicstaticvoidmain(String[] args){for(int i=0;i<2;i++){Thread t =newThread(newMyThread());
t.start();}}
3. 实现Callable接口,用新的类创建Thread实例,调用start
classMyThreadextendsCallable<String>{@OverridepublicStringcall(){//此处为thread执行的任务内容System.out.println(Thread.currentThread().getName());return"执行线程";}}publicstaticvoidmain(String[] args){for(int i=0;i<2;i++){//创建MyThread实例Callable<Integer> c =newMyThread();//获取FutureTaskFutureTask<Integer> ft =newFutureTask<Integer>(c);//使用FutureTask初始化ThreadThread t =newThread(ft);
t.start();// 获取结果String result =ft.get();}}