一、线程的启动方式
1、自己创建Thread类继承Thread类
自己创建的thread要重写run方法,然后启动自己创建的Thread
public class Thread1 extends Thread{
@Override
public void run() {
while(true) {
System.out.println("线程1");
}
}
}
new Thread1().start();
2、自己创建Runnable类实现Runnable接口
自己创建的Runnable要实现run方法,然后把自己创建的Runnable类传入Thread类中
public class Runnable2 implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("线程2");
}
}
}
new Thread(new Runnable2()).start();
3、Thread的匿名内部类
new Thread(()->{
while (true) {
System.out.println("线程3");
}
}).start();
4、利用线程池(随意)传入Runnable匿名内部类
ExecutorService es4 = Executors.newSingleThreadExecutor();
es4.execute(()->{
while (true) {
System.out.println("线程4");
}
});
es4.shutdown();
5、自己创建Callable实现Callable接口:
类似Runnable,区别在有返回值,返回值借助FutureTask实现,FutureTask会存入线程执行结果
public class Callable5 implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(10000);
return "result:"+Thread.currentThread().getName();
}
}
Callable5 c5 = new Callable5();
FutureTask<String> ft5 = new FutureTask<>(c5);
Thread t5 = new Thread(ft5);
t5.start();
try {
String result = ft5.get();//这里会阻塞主线程,直到线程5执行完,返回结果
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
6、利用线程池下的Callable匿名内部类
与线程池的Runnable类似,但是有返回值,返回值存于线程池submit方法的执行结果Future中。
ExecutorService es6 = Executors.newFixedThreadPool(1);
Future<String> f6 = es6.submit(() -> {
Thread.sleep(10000);
return "线程6";
});
try {
f6.get();//这里会阻塞主线程,直到线程6执行完,返回结果
} catch (Exception e) {
e.printStackTrace();
}
es4.shutdown();
二、线程的终止方式
1、volatile
private static volatile boolean stopFlag = false;//默认不中断
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (!stopFlag) {
System.out.println("线程1在执行");
}
});
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
stopFlag = true;
}).start();
}
2、AtomicBoolean
private static AtomicBoolean stopFlag = new AtomicBoolean(false);//默认不中断
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (!stopFlag.get()) {
System.out.println("线程1在执行");
}
});
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
stopFlag.set(true);
}).start();
}
3、Interrupt
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("线程1在执行");
}
});
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
t1.interrupt();
}).start();
}
4、stop
注意stop和interrupt之间的问题:
stop是强制中断,而interrupt不是直接中断,而是做一个中断标识,会做好相关收尾工作再中断。
比如对于一个线程a,当其他线程调用了a的interrupt方法,如果a中在执行wait、sleep等方法,会抛出InterruptedException异常,然后中断。反观stop则会直接中断。
举例说明stop引发问题:
stop对于hashmap扩容直接中断,可能引起数据结构错误。
stop对于io流直接中断,没有正常close关流,会导致内存溢出。