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