首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 企业软件 > 行业软件 >

volatile、synchronized示范

2014-01-26 
volatile、synchronized示例??????????????????? generator.cancel()? ??????????????? }? ??????????? }?

volatile、synchronized示例
??????????????????? generator.cancel();?
??????????????? }?
??????????? }?
??????? }?
?????
??????? public static void test(IntGenerator gp, int count) {?
??????????? ExecutorService exec = Executors.newCachedThreadPool();?
??????????? for (int i = 0; i < count; i++)?
??????????????? exec.execute(new EvenChecker(gp, i));?
??????????? exec.shutdown();?
??????? }?
?????
??????? public static void test(IntGenerator gp) {?
??????????? test(gp, 10);?
??????? }?
?????
??????? public static void main(String[] args) {?
??????????? test(new EvenGenerator());?
??????? }?
??? }</span>?


分析:如果产生偶数的类未加synchronized,那么测试程序将会出现奇数导致退出程序。

?

2、volatile表示原子性,可见性。

????? 对于多个线程之间共享的变量,每个线程都有自己的一份拷贝,当线程1改变变量值时,其他线程并不马上知道该变量值改变了,volatile就保证了变量值对各个线程可见,一个线程改变该值,马上其他线程中该值也改变。原子性表明操作不可中断,如基本变量赋值。

???? 代码示例:
[java] view plaincopy

??? <span style="font-size:16px;">package demo.thread;?
?????
??? public class VolatileDemo implements Runnable {?
?????????
??????? private volatile int i = 0;//volatile设置可见性?
?????
??????? public synchronized? int getValue() {?
??????????? return i;?
??????? }?
?????
??????? private synchronized void enenIncrement() {?
??????????? i++;?
??????????? i++;?
??????? }?
?????
??????? @Override?
??????? public void run() {?
??????????? while (true)?
??????????????? enenIncrement();?
??????? }?
?????
??????? public static void main(String[] args) {?
??????????? VolatileDemo at = new VolatileDemo();?
??????????? new Thread(at).start();?
??????????? while (true) {?
??????????????? int val = at.getValue();?
??????????????? if (val % 2 != 0) {//出现奇数,退出程序?
??????????????????? System.out.println(val+" is not enen!");?
??????????????????? System.exit(0);?
??????????????? }?
??????????? }?
?????
??????? }?
??? }?
??? </span>?


注意i++操作并不是原子行操作,getValue() 方法也要加synchronized 。

热点排行