//通过继承Thread类来创建线程类
public class FirstThread extends Thread
{ private int i ;
//重写run方法,run方法的方法体就是线程执行体
public void run() {
for ( ; i < 100 ; i++ ){System.out.println(getName() + " " + i);}}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
//调用Thread的currentThread方法获取当前线程
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20){
new FirstThread().start();
new FirstThread().start();
} } }}
//通过实现Runnable接口来创建线程类
public class MyRunnable implements Runnable
{
private int i ;
//run方法同样是线程执行体
public void run(){
for ( ; i < 100 ; i++ ){
//当线程类实现Runnable接口时,
//如果想获取当前线程,只能用Thread.currentThread()方法。
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
Runnable接口与Thread构造函数
//通过new Thread(target , name)方法创建新线程
public class Client
{
public static void main(String[] args) {
for (int i = 0; i < 100; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20){
MyRunnable task = new MyRunnable ();
//通过new Thread(target , name)方法创建新线程
new Thread(task , "新线程1").start();
new Thread(task , "新线程2").start();
} }}
// 使用Callable和Future创建线程类
//接口 Callable<Integer>???
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Integer>{
public Integer call() throws Exception {
int i = 0;
for(;i<100;i++){
System.out.println(Thread.currentThread().getName()+"的循环变量I="+i);
}
//call方法可以有返还值,使用泛型来定义返回值
return i;
}}
public static void main(String[] args) {
MyCallable rt = new MyCallable();
FutureTask<Integer> task = new FutureTask<Integer>(rt);
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+"的循环变量I="+i);
if (i==20){
new Thread(task,"有返回值的线程").start();
}}
try{
System.out.println("子线程的返回值="+task.get());
}catch (Exception ex){ ex.printStackTrace();}
}