多线程
- 创建线程有两种方式
1 继承Thread类 并覆写run方法 , run方法 就等于是 新线程中的main方法 - 2 实现Runable接口 并实现run方法
启动线程 : 手动调用线程对象的 start() 方法
1)注意 : 不是调用run方法,而是调用start方法
2)如果调用run方法,并不是启动线程的,只是一个单纯的方法调用
3)当我们调用start方法的时候,会自动开启新的线程并调用run方法
public static void main(String[] args) {
test_02();
}
// 继承方式启动
public static void test_01() {
Thread thread = new Processor();
// 启动该线程,自动调用run方法,切记不能手动调用run方法
thread.start();
// thread.run();
// 到这里 就会有两个线程同时执行
for (int i = 0; i < 10; i++) {
System.out.println("main ---> " + i);
}
}
// 实现的方式启动
public static void test_02(){
Thread thread = new Thread(new Processor1());
// 创建线程有两种,但是启动线程只有一种方式,就是调用该对象的start方法
thread.start();
for (int i = 0; i < 10; i++) {
System.out.println("main ---> " + i);
}
}
}
class Processor1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("run ---> " + i);
}
}
}
class Processor extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("run ---> " + i);
}
}
递归复制目录
思路 :
- 1 文件复制 : 本质就是输入和输出
1) 完成文件输入
2) 完成文件输出
3) 整合输入和输出,完成文件复制
2 递归获取所有的文件
1)获取目录对象
2) 获取目录下面所有子目录
3)获取所有的后代目录
3 整合 1 2
1) 获取后代目录,得到对应 的文件对象
2) 通过文件对象可以获取文件的全路径
3) 生成目录路径,判断目标路径是否存在,不存在就创建
4) 通过全路径就可以创建输入输出流
//文件复制
public static void copy(String src,String target) throws MyException {
if (src.trim().equals(target.trim())){
throw new MyException("源路径和目标路径相同");
}
try {
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(target));
byte[] bytes=new byte[1024];
int a=-1;
while ((a=bi.read(bytes))!=-1){
bo.write(bytes,0,a);
}
bo.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
//递归并复制目录
private static String target=null;
public static void copy(String src,String target) throws MyException {
MyManager.target=target;
check(new File(src));
}
private static void check(File file) throws MyException {
if (file.isFile()){
String absolutePath = file.getAbsolutePath();
String newPath=target+absolutePath.substring(2);
File parentFile = new File(newPath).getParentFile();
if (!parentFile.exists()){
parentFile.mkdirs();
}
MyUtils.copy(absolutePath,newPath);
return;
}
File[] files = file.listFiles();
if (files==null||files.length==0){
File file1 = new File(target + file.getAbsolutePath().substring(2));
file1.mkdirs();
return;
}
for (File file2 : files) {
check(file2);
}
}