[基础] Java 线程相关知识

线程创建的几种方式

  • 继承Thread
  • 实现Runable 接口
  • 实现Callable 接口
  • 利用线程池生成
这几中生成方式的差异
  1. 继承thread 和实现runable 接口,都是无返回值的线程实现方式,Callable 是有明确返回值的
  2. 后面两种可以有返回值,通过Callable接口,就要实现call方法,这个方法的返回值是Object,所以返回的结果可以放在Object对象中
案例
  1. 继承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());
	}
}
  1. 实现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());
	}
}
  1. 实现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 都会让线程进入阻塞状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值