testRunnable.java
package sample;
import org.omg.CORBA.TRANSACTION_MODE;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
public class testRunnable implements Runnable {
boolean mark=false;
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yymmdd");
int count = 0;
System.out.println("Thread start:" + sdf.format(new Date()));
for (int i = 0; i < 1000; i++) {
String flagg = null;
try {
flagg = ppRead(10);
} catch (IOException e) {
e.printStackTrace();
}
if(mark){
try {
ppWrite("1",10);
mark=false;
} catch (IOException e) {
e.printStackTrace();
}
}
if((Integer.valueOf(flagg)==1)){
System.out.println("跳出");
break;
}
count++;
try {
Thread.sleep(1000);
System.out.println(count + "");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread end :" + sdf.format(new Date()));
}
public String ppRead(int readsize) throws IOException {
// 使用nio从本地读取一个文件
//File file = new File();
FileInputStream fileInputStream = new FileInputStream("src/sample/value.pp");
// 获取文件相应的channel,channel中会有相关数据
FileChannel channel = fileInputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(readsize);
// 将channel的数据读取到buffer
channel.read(buffer);
//System.out.println(buffer);
//System.out.println("读取的数据为"+new String(buffer.array()));
fileInputStream.close();
return new String(buffer.array()).trim();
}
public void ppWrite(String content,int writesize) throws IOException {
synchronized (this){
// 将数据写入到文件中
//创建一个输出流
File file = new File("src/sample/value.pp");
FileOutputStream fileOutputStream=new FileOutputStream(file);
// 获取相应的channel
FileChannel channel = fileOutputStream.getChannel();
// 将字符串放入缓存区
ByteBuffer byteBuffer =ByteBuffer.allocate(writesize);
//将字符串以字节形式放入buffer中
byteBuffer.put(content.getBytes());
//开始读取
byteBuffer.flip();
//从buffer中读取到文件
channel.write(byteBuffer);
fileOutputStream.close();
}
}
}
main
package sample;
class propertyT{
static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
testRunnable tr = new testRunnable();
new Thread(tr).start();
testRunnable tr1 = new testRunnable();
new Thread(tr1).start();
testRunnable tr2 = new testRunnable();
new Thread(tr2).start();
Thread.sleep(10000);
tr.mark = true;
}
}
目录结构