线程的启动方式
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class CreateThread {
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("My Thread!");
}
}
static class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("My Runnable!");
}
}
static class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("My Callable!");
return "My Callable Result";
}
}
public static void main(String[] args) {
new MyThread().start();
new Thread(new MyRunnable()).start();
new Thread(()->{
System.out.println("My Lambda!");
}).start();
Thread t = new Thread(new FutureTask<String>(new MyCallable()));
t.start();
ExecutorService service = Executors.newCachedThreadPool();
service.execute(()->{
System.out.println("My ThreadPool!");
});
Future<String> future = service.submit(new MyCallable());
String string = future.get();
service.shutdown();
}
}
线程的6种状态
1、NEW = 创建 线程刚刚创建,还没有启动
2、RUNNABLE=准备状态 可运行状态,由线程调度器安排执行
1、RUNNING=正在执行
2、READY=等待被调度器选中继续执行
3、WAITING=挂起状态 等待被唤醒
wait、join、LockSupport.park、lock
4、TIMED WAITING=睡眠状态 隔一段时间后自动唤醒
sleep(time)、wait(time)、join(time)、LockSupport.parkNanos()、 LockSupport.parkUntil()
5、BLOCKED=被阻塞,等待解锁
synchronized
6、TERMINATED=线程结束
[NEW, TERMINATED, RUNNABLE, BLOCKED, TIMED_WAITING, WAITING]
Yield Join
线程中断
interrupt
interrupt():打断某个线程(设置标志位)原来是false,调用方法后设置为true
--具体怎么做线程内部自己安排
--正在竞争锁的线程是不能进行中断的
使用ReentrantLock的lockInterruptibly方法可以打断
Lock lock = new ReentrantLock();
lock.lockInterruptibly();
isInterrupted():查询线程是否被打断过(查询标志位)
static(静态方法) interrupted():查询当前线程是否被打断过,并重置打断标志位为false
--静态方法执行的是当前线程
睡眠中的线程
sleep()方法先睡眠的时候,不到时间是没有办法叫醒的,这个时候是可以用interrupt设置标志位,然后不许要catch InterruptedException来进行处理,决定是继续睡眠还是别的逻辑(自动进行中断标志复位)
线程结束
1、t.stop()
为什么stop不建议使用,会产生数据不一致的问题:设置A和B,A和B协作,B没有被设置,线程终结束了
释放锁,不处理善后工作
2、t.suspend()暂停,t.resume()恢复执行
已经被废弃,suspend()暂停不会释放锁,容易造成死锁
3、volatile 声明变量控制
只能特定场景下使用,不能适合精确计算场景
如果遇到wait/receive /inspect 是无法控制的
4、interrupted 和volatile类似,通过标识控制
while(!Thread.interrupted())
遇到sleep、wait 处理异常也能正常结束线程
如果需要精确控制计算类型需要另外线程相配合
5、自然结束(能自然结束就尽量自然结束)