一、线程创建的三种方法
1.继承Thread类创建线程类
public class FirstThread extends Thread{
private int i;
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++){
System.out.println(Thread.currentThread().getName());
if(i==2){
new FirstThread().start();
new FirstThread().start();
}
}
}
}
2.实现Runnable接口创建线程类
/*用实现Runnable接口创建的多线程可以共享线程类的实例变量。因为在这种方式下,程序所创建的Runnable只是线程的target,而多个线程可以共享一个target,所以多个线程可以共享一个线程类的实例变量。*/
public class SecondThread implements Runnable{
private int i;
public void run()
{
f在这种or(;i<100;i++){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(Stirng[] args)
{
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName());
if(i==2){
//创建Runable实现对象的类
SecondThread st=new SecondThread();
//以Runable实现类的对象作为Thread的target来创建Thread对象,即线程对象
new Thread(st,"线程1").start();
new Thread(st,"线程2").start();
}
}
}
3.使用Future创建线程
/*1.call方法允许声明抛出异常
*2.call方法允许带返回值
*其他没什么区别*/
public class ThirdThread {
public static void main(String[] args) {
ThirdThread rt=new ThirdThread();
FutureTask<Integer> task=new FutureTask<Integer>((Callable<Integer>)()-> {
int i=0;
for(;i<100;i++) {
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
}
return i;
});
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+i);
if(i==20) {
new Thread(task,"有返回值的线程").start();
}
}
try
{
System.out.println("子线程的返回值:"+task.get());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
4.三种实现方法的比较
二、线程的生命周期