做一个放号器, 多个线程同时申请号码不重复,断电后能恢复.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
比如:
线程1 : 1, 4, 5, 6, 8, 9, 14…
线程2 : 2, 3, 7, 10, 11, 12, 13…
package org.leno.j2se.lesson3.multiThread;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author leno
* 一个简单的放号器, 多个线程同时申请号码不重复,断电后能恢复.
*/
public class SendCode implements Runnable{
//号码
int code = 0;
RandomAccessFile raf = null;
//初始化块
{
try {
raf = new RandomAccessFile("sendCode.txt","rw");
code = raf.readInt();
System.out.println("恢复上次记录:"+code);
} catch (FileNotFoundException e) {
System.out.println("文件找不到!");
}catch (IOException e) {
System.out.println("没有合适的整数值");
}
}
public void run() {
while(true){
synchronized (this) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
code++;
try {
raf.seek(0);//从文件开头以字节为单位测量的偏移量位置,在该位置设置文件指针
raf.writeInt(code);//从文件指针的当前位置开始写
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"申请到号码:"+code);
}
}
}
public static void main(String[] args) {
SendCode sc = new SendCode();
new Thread(sc,"一号线程").start();
new Thread(sc,"二号线程").start();
new Thread(sc,"三号线程").start();
new Thread(sc,"四号线程").start();
}
}