- 论坛徽章:
- 0
|
在java nio 这本书上看到下面一句:
“更妙的是,多个线程可以并发访问同一个文件而不会相互产生干扰。这是因为每次调用都是原子性的(atomic),并不依靠调用之间系统所记住的状态”
所以我就写了下面的程序
- /**
- * $Id$
- * Copyright(C) 2010-2016 bellszhu.com. All rights reserved.
- */
- package bells.nio.channel;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- /**
- * @author <a href="mailto:bellszhu@gmail.com">bellszhu</a>
- * @version 1.0
- * @since 1.0
- * @date: Oct 24, 2012 @time: 10:05:10 PM
- */
- public class TestMultiAccessFile {
- /**
- * @param args
- */
- public static void main(String[] args) throws IOException {
- RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
- String needWriteStr1 = "zzzzzz";
- String needWriteStr2 = "bbbbbb";
- Thread t1 = new Thread(new AccessFile(raf, needWriteStr1), "Thread1");
- Thread t2 = new Thread(new AccessFile(raf, needWriteStr2), "Trhead2");
- t1.start();
- t2.start();
- }
- }
- class AccessFile implements Runnable {
- RandomAccessFile raf;
- String needWriteStr;
- public AccessFile(RandomAccessFile raf, String needWriteStr) {
- this.raf = raf;
- this.needWriteStr = needWriteStr;
- }
- @Override
- public void run() {
- try {
- for (int i = 0; i < needWriteStr.length(); i++) {
- char c = needWriteStr.charAt(i);
- raf.writeChar(c);
- System.out.println(Thread.currentThread().getName() + "--->: " + raf.getFilePointer());
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码 上面这个程序大部分时候输出类似:- Thread1--->: 2
- Thread1--->: 4
- Thread1--->: 6
- Thread1--->: 8
- Thread1--->: 10
- Thread1--->: 12
- Trhead2--->: 14
- Trhead2--->: 16
- Trhead2--->: 18
- Trhead2--->: 20
- Trhead2--->: 22
- Trhead2--->: 24
复制代码 但是有时候会输出类似:
- Thread1--->: 3
- Trhead2--->: 3
- Thread1--->: 5
- Thread1--->: 9
- Trhead2--->: 7
- Trhead2--->: 13
- Trhead2--->: 15
- Trhead2--->: 17
- Trhead2--->: 19
- Thread1--->: 19
- Thread1--->: 21
- Thread1--->: 23
复制代码 因为char是占2个字节的,,所以不太明白为什么会输出下面这类输出?? |
|