线程创建的几种方式
- 继承Thread
- 实现Runable 接口
- 实现Callable 接口
- 利用线程池生成
这几中生成方式的差异
- 继承thread 和实现runable 接口,都是无返回值的线程实现方式,Callable 是有明确返回值的
- 后面两种可以有返回值,通过Callable接口,就要实现call方法,这个方法的返回值是Object,所以返回的结果可以放在Object对象中
案例
- 继承Thread
package test.thread;
public class ThreadImpl extends Thread{
public ThreadImpl() {
}
public void run() {
System.out.println("Thread name :"+Thread.currentThread().getName());
}
public static void main(String args[]) {
ThreadImpl impl = new ThreadImpl();
impl.setName("ThreadImpl");
impl.start();
System.out.println("main Thread name is :"+Thread.currentThread().getName());
}
}
- 实现runable
package test.thread;
public class RunableImpl implements Runnable{
public RunableImpl() {
}
public void run() {
System.out.println("Thread name :"+Thread.currentThread().getName());
}
public static void main(String args[]) {
Thread impl = new Thread(new RunableImpl());
impl.setName("ThreadImpl");
impl.start();
System.out.println("main Thread name is :"+Thread.currentThread().getName());
}
}
- 实现callable 接口
package test.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableImpl implements Callable<User>{
public CallableImpl() {
}
public void run() {
System.out.println("Thread name :"+Thread.currentThread().getName());
}
@Override
public User call() throws Exception {
// TODO Auto-generated method stub
User u1 = new User();
u1.setName("jacdong");
return u1;
}
public static void main(String args[]) throws InterruptedException, ExecutionException {
Callable<User> callableImpl = new CallableImpl();
FutureTask<User> task = new FutureTask<User>(callableImpl);
Thread callThread = new Thread(task);
callThread.start();
if(task.get() != null) {
System.out.println( task.get().getName());
}
}
}
线程状态的转变
五大状态
new , runnable , running , block,dead
runnable 通过os 调度编程running
running 通过yeild 归还cpu 使用权,使线程重新回归runnable。
running 通过wait 实现释放锁,并进入等待队列。也就是在使用wait 的时候,必须先获取锁
running 通过syncronized 进入锁池状态。
sleep 和 join 都会让线程进入阻塞状态