并发编程中可见性问题.pdfVIP

  • 1
  • 0
  • 约1.17万字
  • 约 14页
  • 2026-09-07 发布于北京
  • 举报

线程安全性之可见性有序性

这个案例比较简单,t1线程中使用了stop属性,接着在main线程中修改了stop属性的值以使t1线程终

止,但t1线程并未按预期执行。

public

class

VolatileDemo

{

public

static

boolean

stop=false;

public

static

void

main(String[]

args)

throws

InterruptedException

{

Thread

t1=new

Thread(()‑{

int

i=0;

while(!stop){

i++;

}

});

t1.start();

System.out.println(线程开始启动);

Thread.sleep(1000);

stop=true;

}

}

volatile解决可见性问题

在上述程序中,可通过添加volatile关键字解决,代码如下:

public

class

VolatileDemo

{

public

volatile

static

boolean

stop=false;

public

static

void

main(String[]args)

throws

InterruptedException

{

Thread

t1=new

Thread(()‑{

int

i=0;

w

文档评论(0)

1亿VIP精品文档

相关文档