package com.practise.createthread; public class AnonymousThread { public static void main(String[] args) { new Thread("线程一") { public void run() { for(int i=1;i<=20;i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }.start(); Thread.currentThread().setName("主线程"); for(int i=1;i<=20;i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }
package com.practise.createthread; public class AnonymousThread { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { for(int i=1;i<=20;i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }, "线程二").start(); Thread.currentThread().setName("主线程"); for(int i=1;i<=20;i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }
package com.practise.createthread; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class AnonymousThread { public static void main(String[] args) { FutureTask<Integer> task=new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() { Integer total = 0; try { for (int i = 1; i <= 50; i++) { total += i; } return total; } catch (Exception ex) { ex.printStackTrace(); } return null; } }); new Thread(task, "有返回值的线程").start(); try { System.out.println(task.get()); } catch (Exception ex) { ex.printStackTrace(); } Thread.currentThread().setName("主线程"); for (int i = 1; i <= 20; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }
原文:https://www.cnblogs.com/fengfuwanliu/p/10131481.html