---
title: "线程冲突2"
author: "arne3166"
date: "2010-10-14T11:15:11Z"
tags: []
categories: ["编程语言"]
slug: "2"
draft: false
lastmod: "2010-10-14T11:15:11Z"
id: 784595
url: "https://arne3166.iteye.com/blog/784595"
---

```
import java.io.*;

class DataFile {
	public DataFile() {
		try {
			FileIO.writeOneString( "Hello ","zliner.txt");
		}catch( FileIOException e) {}
	}
	void fileIO() {
		try {
			String str = FileIO.readOneString( "zliner.txt" );
			FileIO.writeOneString( str, "zliner.txt" );
		}catch( FileIOException e) {}
	}
}

class ThreadedFileIO extends Thread {
	DataFile df;
	ThreadedFileIO( String threadName, DataFile d ) {
		df = d;
		setName( threadName );
		start();
	}
	public void run() {
		int i = 0;
		while( i++ < 4 ) {
			try {
				df.fileIO();
				String str = FileIO.readOneString( "zliner.txt" );
				System.out.println( getName() + ";    " + "zliner.txt contains: " + str );
				sleep( 5 );
			}catch( InterruptedException e ) {}
			catch( FileIOException e) {}
		}
	}
}

public class UnsynchedFileIo {
	public static void main(String[] args) {
		DataFile dd = new DataFile();
		new ThreadFileIO( "t0", dd);
		new ThreadFileIO( "t1", dd);
		new ThreadFileIO( "t2", dd);
		new ThreadFileIO( "t3", dd);
		new ThreadFileIO( "t4", dd);
	}	
}
```