一、Java中创建线程方法
1. 继承Thread类创建线程类
定义Thread类的子类,重写该类的run()方法。该方法为线程执行体。 创建Thread子类的实例。即线程对象。 调用线程对象的start()方法启动该线程,示例代码如下:
public class ThreadTest extends Thread{
int i = 0;
//重写run方法,run方法的方法体就是现场执行体
public void run() {
for(;i<10;i++){
System.out.println(i);
}
}
public static void main(String[] args) {
for(int i = 0;i< 10;i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
new ThreadTest().start();
}
}
}
// 或者
public static void main(String[] args) {
for(int i = 0;i< 10;i++) {
new Thread(){public void run() {
System.out.println(Thread.currentThread().getName());
}.start();
}
}
2. 实现Runnable接口创建线程类
定义Runnable接口的实现类,重写该接口的run()方法。该方法为线程执行体。 创建Runnable实现类的实例。并以此实例作为Thread的target来创建Thread对象。该Thread对象才是真正的线程对象。 调用线程对象(该Thread对象)的start()方法启动该线程。
public class RunnableThreadTest implements Runnable {
public void run() {
for(int i = 0;i <10;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
public static void main(String[] args) {
for(int i = 0;i < 100;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
RunnableThreadTest rtt = new RunnableThreadTest();
new Thread(rtt,"新线程1").start();
}
}
}
// 或者
public static void main(String[] args) {
for(int i = 0;i < 100;i++) {
new Thread( new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
}
}
3. 使用Callable和Future创建线程
示例代码如下:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args) {
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for(int i = 0;i < 10;i++) {
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==5) {
new Thread(ft,"有返回值的线程").start();
}
}
try {
System.out.println("子线程的返回值:"+ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception {
int i=0;
for(;i<100;i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
二、创建线程的三种方式的对比
三种方法创建线程各有优劣
1.采用实现Runnable、Callable接口的方式创见多线程
优势:
劣势:
2.使用继承Thread类的方式创建多线程
优势:
劣势:
参考文章:
1. java 并发
原文:http://www.cnblogs.com/wisdo/p/5793277.html