Java中创建线程主要有三种方式:
一、继承Thread类
1、继承Thread,重写run方法。
2、创建Thread子类的实例,创建线程对象。
3、调用start()方法启动线程。
package com.test;
public class FirstThread extends Thread{
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println(this.getName()+"--"+i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"--"+i);
if(i==10){
new FirstThread().start();
new FirstThread().start();
}
}
}
}
二、通过Runnable接口创建线程
1、实现runnable接口,重写run()方法。
2、创建 Runnable实现类的实例,依此实例作为Thread的target来创建Thread对象,该Thread对象才是真正的线程对象。
3、调用start()方法启动线程。
package com.test;
public class SecondThread implements Runnable{
public void run() {
for(int i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"--"+i);
if(i==10){
SecondThread st=new SecondThread();
new Thread(st,"线程1").start();
new Thread(st,"线程2").start();
}
}
}
}
三、通过Callable和Future创建线程
1、实现Callable接口,实现call()方法,该call()方法将作为线程执行体,并且有返回值。
2、创建Callable实例,使用FutureTask包装Callable对象,FutureTask对象封装了Callable对象的call()方法的返回值。
3、FutureTask对象作为Thread对象的target创建并启动新线程。
4、调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。
package com.test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableThread implements Callable<Integer> {
public Integer call() throws Exception {
int i = 0;
for(i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
public static void main(String[] args) {
CallableThread ct = new CallableThread();
FutureTask<Integer> ft = new FutureTask<Integer>(ct);
for(int i = 0;i < 20;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
if(i==10){
new Thread(ft,"返回值的线程").start();
}
}
}
}