public class ThreadDemo1 extends Thread{ @Override public void run() { // TODO Auto-generated method stub System.out.println("继承Thread实现多线程"+Thread.currentThread().getName()); }}
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub ThreadDemo1 threadDemo1=new ThreadDemo1(); threadDemo1.setName("demo1"); threadDemo1.start(); System.out.println("主线程名称"+Thread.currentThread().getName()); }}
public class ThreadDemo2 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("通过Runnable实现多线程,名称:"+Thread.currentThread().getName()); }}
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub //ThreadDemo1 threadDemo1=new ThreadDemo1(); ThreadDemo2 threadDemo2 =new ThreadDemo2(); Thread thread =new Thread(threadDemo2); thread.setName("demo2"); thread.start(); System.out.println("主线程名称"+Thread.currentThread().getName()); }}
使用Lambda表达式创建匿名内部类线程
public class Main { public static void main(String[] args) { //匿名内部类使用Lambda表达式 Thread thread2=new Thread(()->{ System.out.println("通过Runnable实现多线程,名称"+Thread.currentThread().getName()); }); thread2.setName("demo2,Lambda"); thread2.start(); System.out.println("主线程名称"+Thread.currentThread().getName()); }}
public class Main2 { public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService executorService=Executors.newFixedThreadPool(3); for(int i=0;i<10;i++) { executorService.execute(new ThreadDemo4()); } System.out.println("主线程名称"+Thread.currentThread().getName()); //关闭线程池 executorService.shutdown(); }}
public class ThreadDemo4 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("通过线程池+Runnable实现多线程,名称:"+Thread.currentThread().getName()); }}