优雅的停止线程
停止线程有stop,destroy等。
这些方法已经被停用。因为这些方法会造成线程的死锁。
推荐用下面这种
public class ThreadElegantStop{
public static boolean flag = true;
public static void main(String[] args){
new Thread(()->{
long num = 0;
while(flag){
try{
Thread.sleep(50);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行 ,num="+num++);
}
},"本线程").start();
try{
Thread.sleep(200);
}catch(InterruptedException e){
e.printStackTrace();
}
flag=false;
}
}
主要思想就是通过逻辑来使线程提前停止
后台守护线程
就是当被守护线程进行则守护线程进行。被守护线程线程结束,守护线程就结束。守护线程运行时间<=被守护线程。
public class ThreadDaemon{
public static void main(String[] args){
new Thread(()->{
for(int x=0;x<10;x++){
try{
Thread.sleep(50);
}catch(InterruptedException e){
e.printStackTrace();
}
}
},"被守护线程").start();
Thread deamonThread = new Thread(()->{
for(int x=0;x<10;x++){
try{
Thread.sleep(50);
}catch(InterruptedException e){
e.printStackTrace();
}
}
},"守护线程").start();
deamonThread.setDeamon(true);
deamonThread.start();
}
}
volatile
原本程序操作的是一个寄存器中的数据,操作完后把寄存器的值再赋给原本的变量。
但是用了volatile定义变量后,程序就是直接操作变量。
如果一个线程在改变了主存中的值,但是另一个还在改变寄存器中的值,那么就会造成数据不同步。
class Mythread16 implements Runnable {
private volatile int ticket = 1000;
@Override
public synchronized void run(){
while(this.ticket>0){
try{
Thread.sleep(0);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票结果,ticket="+ticket--);
}
}
}
public class ThreadVolatile{
public static void main(String[] args){
Mythread16 mythread16 = new Mythread16();
new Thread(mythread16,"A").start();
new Thread(mythread16,"B").start();
new Thread(mythread16,"C").start();
}
}