File 线程读写

1.Exception in thread "main" java.lang.IllegalMonitorStateException: current thread not owner??

 

public synchronized void setRunning(boolean flag)

 

 public class FileWriterThread extends Thread{
 private FileThread fileThread;
 private int i;
 
 public FileWriterThread(FileThread fileThread){
  this.fileThread=fileThread;
 }
 public void run() {
  while(true){
   i++;
   synchronized (fileThread){
   try {
    //Thread.sleep(100);
    if(!fileThread.isRead()){
     fileThread.wait();
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("write:  ................");
   fileThread.notifyAll();
   fileThread.setRead(false);
   if(i>10){
    break;
   }}}}

 

import java.io.IOException;

public class FileReaderThread extends Thread{
 private FileThread fileThread;
 private int i;
 
 public FileReaderThread(FileThread fileThread){
  this.fileThread=fileThread;
 }

 public void run() {
  while(true){
   i++;
   synchronized (fileThread){
   try {
    //Thread.sleep(100);
    if(fileThread.isRead()){
     fileThread.wait();
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("read:    .................");
   
   fileThread.setRead(true);
   if(i>10){
    break;
   }
   fileThread.notifyAll();}}}

 

public class FileThread {

 private FileInputStream fis;
 private FileOutputStream fos;
 private byte[] buf;
    volatile int len;
 private boolean isRead;
 
 public FileThread(byte[] buf){
  try {
   fis=new FileInputStream("c:\\a.txt");
   fos=new FileOutputStream("c:\\aa.txt");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  this.buf=buf;
 }
 
 public boolean isRead() {
  return isRead;
 }

 public void setRead(boolean isRead) {
  this.isRead = isRead;
 }}}

 

public class Test {

 public static void main(String[] args) {
  byte[] buf=new byte[1024];

  FileThread ft=new FileThread(buf);
  
  
  FileReaderThread frt=new FileReaderThread(ft);
  frt.start();
  FileWriterThread fwt=new FileWriterThread(ft);
  fwt.start();}}

两个线程同步运行:

read:    .................
write:  ................
read:    .................
write:  ................
read:    .................

 

2.把上面的类写在spring2中:

<bean id="file" class="thread.two.FileThread" scope="singleton"></bean>
<bean id="read" class="thread.two.FileReaderThread">
 <constructor-arg ref="file"></constructor-arg>
</bean>
<bean id="write" class="thread.two.FileWriterThread">
 <constructor-arg ref="file"></constructor-arg>
</bean>

[B@df1832 read---- len:1024
getLen()----- 1024
write: len=1024           //线程没有执行完,没有做循环 ??后来又看出来了,它执行的好慢.

 

private TaskExecutor taskExecutor;

taskExecutor.execute(new MessagePrinterTask("Message" + i));//MessagePrinterTask实现Runnable

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值