-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsample_volatile.java
executable file
·44 lines (41 loc) · 1.36 KB
/
sample_volatile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//import java.io.*;
//import java.util.*;
class my_class{
public String s1;
// ýòî âíóòðåííÿ äèðåêòèâà äëÿ êîìïèëÿòîðà, íèêàê íå ïðîÿâëÿåòñÿ,
// ñëóæèò äëÿ ïîñòîÿííîãî îòîáðàæåíèÿ ðåàëüíîãî çíà÷åíèÿ,
// à íå êàê êîíñòàíòà ìåæäó îäíèì ïðèñâàèâàíèå è âòîðûì, êîãäà êîìïèëÿòîð âèäèò åå êàê êîíñòàíòó
// è åñëè íå ñòîèò volatile, òî èçìåíåíèÿ â ýòî âðåìÿ äðóãèì ïîòîêîì íå äàäóò ðåçóëüòàòà
// boolean volatile value=true;
// while(value){System.out.println(++i)};
// åñëè îáðàòèòüñÿ êàê this.value=false âûéäåò èç öèêëà, åñëè óáðàòü volatile - âû÷íûé öèêë
public volatile String s2;// ïåðåìåííàÿ, êîòîðàÿ ìîæåò áûòü èçìåíåíà â ëþáîå âðåìÿ äðóãèì ïîòîêîì
my_class(String s1,String s2){
this.s1=s1;
this.s2=s2;
}
}
class my_thread implements Runnable{
private my_class temp=null;
private String name=null;
my_thread(my_class temp,String thread_name){
this.temp=temp;
this.name=thread_name;
(new Thread(this)).start();
}
public String toString(){
return name+" s1:"+temp.s1+" s2(volatile):"+temp.s2;
}
public void run() {
System.out.println(this);
this.temp.s2=this.name;
System.out.println(this);
}
}
public class temp {
public static void main(String args[]){
my_class temp=new my_class("string one","string two");
my_thread one=new my_thread(temp,"one");
my_thread two=new my_thread(temp,"two");
}
}