一、线程简介
1.线程的概念
系统运行的最小单元
2.为何使用多线程
更好地利用系统资源(处理器多核心),提高响应速度。
3.线程的状态
NEW(创建状态)
RUNABLE(运行状态,系统调度,争抢时间片)
BLOCKED(阻塞状态,加了锁,其它线程获得到了锁)
WATING(等待状态,wait()方法时,使用notify()唤醒)
TIMED_WAITING(超时等待状态,线程sleep()时,)
TERMINAL(线程终止)
关于wait和notify:
public class ThreadTest { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Waiting(), "WaitingThread"); Thread thread2 = new Thread(new NotifyWaiting(), "NotifyWaitingThread"); thread.start(); TimeUnit.SECONDS.sleep(2); thread2.start(); } } class Waiting implements Runnable { @Override public void run() { synchronized (Waiting.class) { try { System.out.println("Current thread: " + Thread.currentThread().getName() + ",Waiting is waiting!"); Waiting.class.wait(); System.out.println("Current thread: " + Thread.currentThread().getName() + ",Waiting is notified!"); } catch (InterruptedException e) { e.printStackTrace(); } } } } class NotifyWaiting implements Runnable { @Override public void run() { synchronized (Waiting.class) { Waiting.class.notify(); System.out.println("Current thread: " + Thread.currentThread().getName() + ",Waiting is notified!"); } } }
结果:
Current thread: WaitingThread,Waiting is waiting! Current thread: NotifyWaitingThread,Waiting is notified! Current thread: WaitingThread,Waiting is notified!
wait方法会释放锁,sleep则不会
二、启动和终止线程
1.启动线程
1.构建线程
new Thread(); new Runable(); new Callable(); //Callable可以返回Future携带返回值
注意:最好给线程初始化名称,方便JVM分析。
2.启动线程
thread.start();
或者Excutors.new线程池,然后ExecutorService.submit或者excute
2.终止线程
终止线程最好使用一个volatile修饰的boolean开关去进行控制