第一种,继承Thread类创建线程,重写run方法。【通过观察Thread类源码,发现Thread实际上是实现了Runnable接口的一个实例,即 代表一个线程的实例。启动线程:调用start()方法即可;start()方法与run()的区别在于:start()(开辟一个新的线程)运行在子线程 中;run()运行在原线程;】

创建线程的四种方法_线程池

public class MyThread extends Thread{
@Override
public void run() {
for (int i=0;i<10;i++){
System.out.println("myTRhread执行了:"+System.currentTimeMillis());
}
}
}

测试创建这个线程:
public class ThreadCreateDemo {
public static void main(String[] args) {
//方式一:继承Thread
MyThread myThread=new MyThread();
myThread.start();
for (int i=0;i<10;i++){
System.out.println("main主线程执行了"+System.currentTimeMillis());
}
}
}

第二种:实现 Runnable 接口,重写run方法;

实现 Runnable 接口比继承 Thread 类所具有的优势:

1:适合多个相同的程序代 码的线程去处理同一个资源

2:可以避免 java 中的单继承的限制

3:增加程序的健壮 性,代码可以被多个线程共享,代码和数据独立

4:线程池只能放入实现 Runable 或callable 类线程,不能直接放入继承 Thread 的类

5:runnable 实现线程可以对线 程进行复用,因为 runnable 是轻量级的对象,重复 new 不会耗费太大资源,而 Threa d 则不然,它是重量级对象,而且线程执行完就完了,无法再次利用

public class MyRunnable implements  Runnable{
public void run() {
for (int i=0;i<10;i++){
System.out.println("执行时间是:"+System.currentTimeMillis()+";执行次数是:"+i);
}
}
}

测试创建这个线程
public class ThreadCreateDemo {
public static void main(String[] args) {
for (int i=0;i<10;i++){
System.out.println("main主线程执行了"+System.currentTimeMillis());
}
Thread thread=new Thread(new MyRunnable(),"myrunable");
thread.start();
}
}


第三种:实现Callable接口通过FutureTask包装器实现创建线程

public class MyCallable implements Callable<String> {

public String call() throws Exception {
for (int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"执行时间是:"+System.currentTimeMillis()+";循环次数是:"+i);
}
return "myCallable接口执行完成";
}
}


public class ThreadCreateDemo {
public static void main(String[] args) {
//方式三:实现Callabl接口
FutureTask<String> task=new FutureTask<String>(new MyCallable());
Thread thread=new Thread(task,"MyCallable");
thread.start();
for (int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"执行时间:"+System.currentTimeMillis()+";执行次数是:"+i);
}

String result= null;
try {
result = task.get();
System.out.println("MyCallable执行结果是:"+result);
} catch (InterruptedException e){
e.printStackTrace();
} catch (ExecutionException e){
e.printStackTrace();
}
}
}

第四种:通过线程池创建对象,通过Executors的静态方法创建线程池

public class MyThread extends Thread{
@Override
public void run() {
for (int i=0;i<10;i++){
System.out.println("myTRhread执行了:"+System.currentTimeMillis());
}
}
}


public class ThreadCreateDemo {
public static void main(String[] args) {
//使用线程池创建线程
//使用Excutors获取线程池对象
ExecutorService executorService = newFixedThreadPool(10);
executorService.execute(new MyRunnable());
for (int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"执行时间:"+System.currentTimeMillis()+";执行次数是:"+i);
}
}
}