1. 继承Thread类
package test;import java.util.concurrent.TimeUnit;public class Test extends Thread{public void run() {for(int i=0;i<10;i++){try {
TimeUnit.SECONDS.sleep(2);
System.out.println("线程啊!"+Thread.currentThread().getName());} catch (InterruptedException e) {
e.printStackTrace();}}}public static void main(String[] args) {
Test myThread1 = new Test();
Test myThread2 = new Test();
myThread1.start();
myThread2.start();}}
2.实现Runnable接口
package test;import java.util.concurrent.TimeUnit;public class Test implements Runnable{public void run() {for(int i=0;i<10;i++){try {
TimeUnit.SECONDS.sleep(2);
System.out.println("线程啊!"+Thread.currentThread().getName());} catch (InterruptedException e) {
e.printStackTrace();}}}public static void main(String[] args) {
Thread myThread1 = new Thread(new Test());
Thread myThread2 = new Thread(new Test());
myThread1.start();
myThread2.start();}}
3.实现Callable接口 通过FutureTask创建线程 可以获取线程返回结果
package test;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;import java.util.concurrent.TimeUnit;public class Test implements Callable<String>{public String call() {try {
TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {
e.printStackTrace();}return "测试Callable";}public static void main(String[] args) {
Test test = new Test();
FutureTask<String> ft = new FutureTask<String>(test);
Thread thread = new Thread(ft);
thread.start();try{
System.out.println(ft.get());}catch(Exception e){
e.printStackTrace();}}}
4.使用ExecutorService
import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;public class Test implements Callable<String> {public String call() {try {
TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {
e.printStackTrace();}return "测试Callable";}public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<String> f = pool.submit(new Test());
pool.shutdown();try {// 有返回值 阻塞等待
System.out.println(f.get());} catch (Exception e) {
e.printStackTrace();}
ExecutorService pool2 = Executors.newFixedThreadPool(1);//不阻塞
pool2.execute(new testR());}}class testR implements Runnable {@Overridepublic void run() {
System.out.println("测试线程!!");}}