一.通过继承Thread类实现
1.子类SubThread继承Thread
2.重写run()方法:子线程的执行体
3.创建子类SubThread,并调用start():启动线程
public class subThread1 extends Thread{
public subThread1(){
System.out.println("构造函数");
}
int i = 0;
// 重写run() 方法
public void run(){
for(; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args){
for(int j = 101; j < 150; j++){
System.out.println(Thread.currentThread().getName() + " : " + j);
if(120 == j){
// 创建2个子线程,并执行
new subThread1().start();
new subThread1().start();
}
}
}
}
1.创建实现Runnable接口的实现类
2.定义run()方法:子线程执行体
3.将实现类对象作为target传给Thread类, Thead对象调用start()启动线程
public class subThread2 implements Runnable{
int i = 0;
public void run(){
for(; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args){
subThread2 st2 = new subThread2();
for(int j = 101; j < 150; j++){
System.out.println(Thread.currentThread().getName() + " " + j);
if(120 == j){
// Runnable实现类的对象作为Thread的target创建Thread对象, sub1指定线程名
new Thread(st2, "sub1").start();
new Thread(st2, "sub2").start();
}
}
}
}
三.实现Callable接口
1.定义Callable接口的实现类,并实现call()方法:子线程的执行体, 该方法可以有返回值,并可以抛出异常
2.创建实现类的实例,作为FutureTask类实例的target
3.将FutureTask类实例作为Thread类实例的target, 调用start():执行子线程
4.调用FutureTask类实例的get()方法获取子线程执行(call())的返回值
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
// Callable必须指定泛型
public class subThread3 implements Callable<Integer>{
int i = 0;
// 子线程的执行体, 可以有返回值, 并能抛异常, 返回类型必须与Callable定义的泛型一致
public Integer call(){
for(; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
public static void main(String[] args){
subThread3 st3 = new subThread3();
// Future接口(Callable接口call方法的返回值)的实现类,FutureTask并实现了Runnable接口, 可作为Thread的Target
// get()为call()方法的返回值
FutureTask<Integer> ft = new FutureTask<Integer>(st3);
for(int j=101; j < 150; j++){
System.out.println(Thread.currentThread().getName() + " " + j);
if(120 == j){
// 作为Thread的Target, start()执行线程
new Thread(ft).start();
}
}
try{
System.out.println("子线程执行后,i的值: " + ft.get());
}catch(Exception e){
e.printStackTrace();
}
}
}