任何线程池模型都不会内置临界保护机制,因为不同业务场景下临界保护的方式很多,对性能影响很大,所以需要自己手动去做。
Java中不同的线程是可以同时 *** 作一个文件的,只不过有时候因为进程执行的快慢,会出现数据读取不同步的问题,例子如下:Public class Readfile implements Runnable{ public void run(){ FileInputStream inputStream = new FileInputStream(file)//读数据 byte[] buffer = new byte[1024] int size while ((size = inputStream.read(buffer)) >0) { outputStream.write(buffer, 0, size)//写数据 } inputStream.close()// outputStream.close()} public satatic void main(String args []) throws InterruptedException{ Readfile rf = new Readfile() Thread t1 = new Thread(rf)//开启一个线程 Thread t2 = new Thread(rf)//开启第二个线程 t1.start() t2.start()}}#include <io.h>#include <sys/types.h>
#include <sys/stat.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
int fh, numread
char buffer[40]
/* Quit if can't open file or system doesn't
* support sharing.
*/
fh = _sopen( "locking.c", _O_RDWR, _SH_DENYNO,
_S_IREAD | _S_IWRITE )
if( fh == -1 )
exit( 1 )
/* Lock some bytes and read them. Then unlock. */
if( _locking( fh, LK_NBLCK, 30L ) != -1 )
{
printf( "No one can change these bytes while I'm reading them\n" )
numread = _read( fh, buffer, 30 )
printf( "%d bytes read: %.30s\n", numread, buffer )
lseek( fh, 0L, SEEK_SET )
_locking( fh, LK_UNLCK, 30L )
printf( "Now I'm done. Do what you will with them\n" )
}
else
perror( "Locking failed\n" )
_close( fh )
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)