代码实现,展现使用stop方法停止线程,出现数据不一致的情况:
资源类:
public class Book {
private Long createTime;
private Long updateTime;
public Book() {
this.createTime = 0l;
this.updateTime = 0l;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
public Book(Long createTime, Long updateTime) {
this.createTime = createTime;
this.updateTime = updateTime;
}
@Override
public String toString() {
return "Book{" +
"createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}
读数据线程实现类:
public class ReadThread extends Thread{
private Book book;
public ReadThread(Book book){
this.book = book;
}
@Override
public void run() {
while (true){
synchronized (book){
if (book.getCreateTime() != book.getUpdateTime()) {
System.out.println(book.toString());
}
}
Thread.yield();
}
}
}
写入线程实现类:
public class WriteThread extends Thread{
private Book book;
public WriteThread(Book book){
this.book = book;
}
@Override
public void run() {
while (true){
synchronized (book){
long time = new Date().getTime();
book.setCreateTime(time);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
book.setUpdateTime(time);
}
Thread.yield();
}
}
}
线程启动类:
public static void main(String[] args) throws InterruptedException {
Book book = new Book();
ReadThread readThread = new ReadThread(book);
readThread.start();
while (true) {
Thread thread = new WriteThread(book);
thread.start();
Thread.sleep(100);
thread.stop();
}
}
正常停止线程方式:
public class StopThread1 extends Thread {
//自定义标记,来停止线程
private volatile boolean flag = true;
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
System.out.println("i = " + i);
if (!flag) {
System.out.println("最终停止了--" + i);
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
StopThread1 t1 = new StopThread1();
t1.start();
Thread.sleep(10);
t1.flag = false;
}
}