一、继承Thread创建线程:
package com.cloud;
public class TheadDemo {
private static class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 继承Thread创建线程");
}
}
public static void main(String[] args) {
MyThread td = new MyThread();
td.setName("td1");
td.start();
MyThread td2 = new MyThread();
td2.setName("td2");
td2.start();
}
}
运行结果:
td2 继承Thread创建线程
td1 继承Thread创建线程
二、实现Runnable接口:
public class MyThread{
public static void main(String[] args) {
MyThreadDemo t1 = new MyThreadDemo();
Thread th1 = new Thread(t1,"th1");
Thread th2 = new Thread(t1,"th2");
Thread th3 = new Thread(t1,"th3");
th1.start();
th2.start();
th3.start();
}
static class MyThreadDemo implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 实现Runnable创建的线程");
}
}
}
运行结果:
th1 实现Runnable创建的线程
th2 实现Runnable创建的线程
th3 实现Runnable创建的线程
public class MyThread{
public static void main(String[] args) {
//此写法不推荐
MyThreadDemo t1 = new MyThreadDemo();
MyThreadDemo t2 = new MyThreadDemo();
MyThreadDemo t3 = new MyThreadDemo();
Thread th1 = new Thread(t1,"th1");
Thread th2 = new Thread(t2,"th2");
Thread th3 = new Thread(t3,"th3");
th1.start();
th2.start();
th3.start();
}
static class MyThreadDemo implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 实现Runnable创建的线程");
}
}
}
运行结果:
th1 实现Runnable创建的线程
th2 实现Runnable创建的线程
th3 实现Runnable创建的线程
三、实现Callable接口创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureTaskDemo {
static class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 100;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
new Thread(futureTask,"a").start();
System.out.println("获取返回值="+futureTask.get());
}
}
运行结果:
获取返回值=100
四、线程池创建线程
import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
import edu.emory.mathcs.backport.java.util.concurrent.Executors;
public class PoolThread {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
pool.submit(new Runnable() {
@Override
public void run() {
//执行业务逻辑
for(int i = 1; i <= 5; i++) {
System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" );
}
}
});
pool.submit(new Runnable() {
@Override
public void run() {
//执行业务逻辑
for(int i = 6; i <= 10; i++) {
System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务");
}
}
});
}
}
运行结果:
线程:pool-1-thread-1执行了任务1~
线程:pool-1-thread-1执行了任务2~
线程:pool-1-thread-1执行了任务3~
线程:pool-1-thread-1执行了任务4~
线程:pool-1-thread-1执行了任务5~
线程:pool-1-thread-2执行了任务6~
线程:pool-1-thread-2执行了任务7~
线程:pool-1-thread-2执行了任务8~
线程:pool-1-thread-2执行了任务9~
线程:pool-1-thread-2执行了任务10~