Xin hỏi về volatile trong xử lí đa luồng java
Em chào a, e là Tú, e có biết nhóm Unity ạ. E đang đọc và thực hiện lại 1 số ví dụ của a trong trang này của a <span style="vertical-align: inherit"><span style="vertical-align: inherit">https://tvd12.com/volatile-and-atomic/</span></span> . Em đang bị đánh giá ở phần VolatileVí dụ khi em thử bỏ qua biến biến trong biến hoạt động thì luồng 2 của em vẫn hoạt động bình thường, e không hiểu tại sao, mong a chỉ dẫn
threadjava
Remain: 5
2 Answers
monkey
Enlightened
monkey
Enlightened
ý em là code thế này:
private boolean active;
public void prepare() throws InterruptedException {
new Thread(() -> {
System.out.println("application preparing ...");
sleep(3);
active = true;
})
.start();
}
public void start() throws Exception {
new Thread(() -> {
while(!active);
System.out.println("application started");
})
.start();
}
Nó vẫn in được application started đúng không em?
-
1
Tú Đình
Beginner
Tú Đình
Beginner
package dev.ozudo.volatile_atomic;
public class VolatileExample
{
private boolean active;
public void prepare() throws InterruptedException{
new Thread(()->{
System.out.println("application preparing");
System.out.println("name = "+Thread.currentThread().getName());
sleep(5);
active = true;
}).start();
}
public void start() throws Exception{
new Thread(()->{
long time = System.currentTimeMillis();
while (!active){
// System.out.println("application started");
}
if(active){
System.out.println("name = "+Thread.currentThread().getName());
System.out.println("stop app = "+(System.currentTimeMillis()-time));
}
}).start();
}
public void start2() throws Exception{
new Thread(()->{
long time = System.currentTimeMillis();
while (!active){
// System.out.println("application started");
}
if(active){
System.out.println("name = "+Thread.currentThread().getName());
System.out.println("stop app 2222 = "+(System.currentTimeMillis()-time));
}
}).start();
}
private static void sleep(int seconds){
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
VolatileExample example = new VolatileExample();
example.prepare();
example.start();
example.start2();
sleep(1);
}
}
-
0