在java多线程的使用中,如果通过共享变量实现java的中断或者有共享变量,要通过关键字volatile 修饰。
在java虚拟机中,共享变量保存在主存中,但是线程在访问变量的时候一般是访问主存变量的副本,于是,当我们要停止某个线程的时候,通过改变共享变量可以实现。
但是为什么要使用volatile关键字修饰?用一般变量修饰行不行?答案也是可以的,因为现在的计算机运行速度很快,一般看不出差异很大,但是有些计算机不使用volatile修饰,会出现问题。
在修改变量1时,如果使用的是一般变量1,而修改的是某个线程的变量1副本,而其他线程的副本还是属于原来的值,想要修改主存和其他线程的副本需要一段时间,但是在一般的计算机看不出来差别。
如果想要直接修改主存的变量1,可以通过关键字volatile快速实现,然后其他线程的副本也会快速修改。
package JavaFile;
public class Test {
public static void main(String [] args) throws InterruptedException{
System.out.println("main start!");
Thread1 the = new Thread1();
the.start();
Thread.sleep(1000);
System.out.println("main end!");
the.running = false;
}
}
class Thread1 extends Thread{
public volatile boolean running = true;
public void run(){
System.out.println("Thread1 start!");
int counter=0;
while(running){ //当running 为false时结束进程
try {
Thread.sleep(100);
} catch (Exception e) {}
counter++;
System.out.println(counter+"Thread");
}
System.out.println("Thread1 end!");
}
}
运行结果如下:
main start!
Thread1 start!
1Thread
2Thread
3Thread
4Thread
5Thread
6Thread
7Thread
8Thread
9Thread
main end!
10Thread
Thread1 end!