Monday, July 9, 2018

volatile usage --problem

import java.util.ArrayList;



public class ThreadTest {

public static void main(String[] args) {

ArrayList arr = new ArrayList();

TestTwo bobj = new TestTwo();

for (int  i =0; i<10 font="" i="">
arr.add(new MyTh(i,bobj));


for (int  i =0; i<10 font="" i="">
{
((Thread ) arr.get(i)).start();


}

}

}



class MyTh extends Thread{


int  num ;

static int  age ;


volatile StringBuffer buff = new StringBuffer("0");

static  StringBuffer buff2 = new StringBuffer("0");

TestTwo obj ;

MyTh (int  k, TestTwo cobj )

{this.num=k; 
this.obj=cobj;} 

@Override
public void run() {

if(this.num==6){
//setAge(40);
this.obj.count.append("hi");
this.buff.append("hi");
this.buff2.append("hi");
this.age =40;
    }
System.out.println(Thread.currentThread().getName() + " :"+this.num + ":" + this.age +":"+
" :[" +this.buff2 +":"+ this.buff2.hashCode() + 
    "] : [" + this.buff + " :"+ this.buff.hashCode() +"] :[ "+ this.obj.count+ ":"+this.obj.count.hashCode() +":]");

}

int   getAge(){
return age;
}

void  setAge(int  k){
this.age =k;
}

}


class TestTwo {

volatile StringBuffer count = new StringBuffer("0");


}


------------



Thread-0 :0:0: :[0:1740525517] : [0 :1769581898] :[ 0:1833313469:]
Thread-1 :1:0: :[0:1740525517] : [0 :857628581] :[ 0:1833313469:]
Thread-2 :2:0: :[0:1740525517] : [0 :1498557318] :[ 0:1833313469:]
Thread-3 :3:0: :[0:1740525517] : [0 :1419206900] :[ 0:1833313469:]
Thread-4 :4:0: :[0:1740525517] : [0 :313434985] :[ 0:1833313469:]
Thread-5 :5:0: :[0:1740525517] : [0 :1644604984] :[ 0:1833313469:]
Thread-6 :6:40: :[0hi:1740525517] : [0hi :1055613344] :[ 0hi:1833313469:]
Thread-7 :7:40: :[0hi:1740525517] : [0 :1151033700] :[ 0hi:1833313469:]
Thread-8 :8:40: :[0hi:1740525517] : [0 :1472482392] :[ 0hi:1833313469:]
Thread-9 :9:40: :[0hi:1740525517] : [0 :1908885604] :[ 0hi:1833313469:]