public static void main(String[] args) { noAnonymity(); }
// 匿名创建多线程 public static void anonymity(){ for (int i = 0; i < 10; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName() + "\t 创建线程"); }).start(); } } // 非匿名创建多线程 public static void noAnonymity(){ for (int i = 0; i < 10; i++) { new MyThread().start(); } } }
class MyThread extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName() + "\t 创建线程"); } }
class RunnableTest { public static void main(String[] args) { anonymity(); }
// 匿名创建 public static void anonymity(){ for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"\t 创建线程"); } }).start(); } }
// 非匿名创建 public static void unAnonymity(){ for (int i = 0; i < 10; i++) { Thread thread = new Thread(new MyRunnable()); thread.start(); } } }
class MyRunnable implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"\t 创建线程"); } }
4.3、实现Callable接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class CallableTest { public static void main(String[] args) throws ExecutionException, InterruptedException { for (int i = 0; i < 10; i++) { FutureTask<Integer> futureTask = new FutureTask<>(new MyCallableTest()); new Thread(futureTask).start(); System.out.println(futureTask.get()); } } }
class MyCallableTest implements Callable<Integer>{ @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName() +"\t 创建线程"); return 1; } }
public class TimerTest { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("系统启动时间:"+sdf.format(date)); Calendar newTime = Calendar.getInstance(); newTime.setTime(date); // 加5秒 newTime.add(Calendar.SECOND,5); Date time = newTime.getTime(); System.out.println("预计定时器启动时间"+sdf.format(time));
public class SpringThreadTest { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class); SpringAsyncService bean = ac.getBean(SpringAsyncService.class); bean.AsyncA(); bean.AsyncB(); } }