1.多线程传文件
public class Test3 extends Thread {
private File file;
private File target;
private int len;
public Test3(File file, File target ,int len) {
this.file = file;
this.target = target;
this.len=len;
}
public void run(){
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(file);
fos=new FileOutputStream(target,true);
byte[] c=new byte[len];
int tmp;
long total=fis.available();
double loaded=0;
while((tmp=fis.read(c))!=-1){
fos.write(tmp);
loaded+=tmp;
double per=loaded/total;
double persent= (int)(per*10000)/100.0;
System.out.println(file.getName()+"已读取"+persent+"%");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
public static void main(String[] args) {
Test3 t1=new Test3(new File("a.txt"),new File("x.txt"),1000);
Test3 t2=new Test3(new File("b.txt"),new File("y.txt"),3000);
Test3 t3=new Test3(new File("c.txt"),new File("z.txt"),5000);
t1.start();
t2.start();
t3.start();
}
}
2.生产者-仓库-消费者
public class Test4 {
public static void main(String[] args) {
Storage sg=new Storage();
Woker w=new Woker();
w.s=sg;
Customer c=new Customer();
c.s=sg;
w.start();
c.start();
}
}
class Woker extends Thread{
Storage s;
public void run(){
while (true) {
s.addStore();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customer extends Thread{
Storage s;
public void run(){
while (true) {
s.minusStore();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Storage{
public int stores=10;
public synchronized void addStore(){
if(stores>=20){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
stores++;
System.out.println(Thread.currentThread().getName()+"生产产品,当前库存为:"+stores);
notifyAll();
}
}
public synchronized void minusStore(){
if(stores<0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
stores--;
System.out.println(Thread.currentThread().getName()+"消费产品,当前库存为"+stores);
notifyAll();
}
}
}