IT评测·应用市场-qidao123.com技术社区

标题: 重温java 系列一 Java根本 [打印本页]

作者: 傲渊山岳    时间: 2025-4-8 16:21
标题: 重温java 系列一 Java根本
文件拷贝的5种方式

传统字节拷贝

  1. public static void main(String[] args) throws IOExecption{
  2.     try(InputStream is = new FileInputStream("source.txt");
  3.         OutputStream os = new FileOutputStream("target.txt")){
  4.         
  5.         byte[] buffer = new byte[1024];
  6.         int length;
  7.         while ((length = is.read(buffer))>0){
  8.             os.write(buffer,0,length);
  9.         }
  10.         
  11.     }
  12. }
复制代码

缓冲流优化拷贝

  1. public static void main(String[] args) throws FileNotFoundException {
  2.         try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("source.txt"));
  3.              BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("target.txt"))
  4.         ){
  5.             byte[] buffer = new byte[1024];
  6.             int len;
  7.             while ((len = bis.read(buffer)) != -1) {
  8.                bos.write(buffer, 0, len);
  9.             }
  10.         } catch (IOException e) {
  11.             throw new RuntimeException(e);
  12.         }
  13.     }
复制代码

Java NIO 拷贝

  1. public static void main(String[] args) throws IOException {
  2.         Path source = Paths.get("source.txt");
  3.         Path target = Paths.get("target.txt");
  4.         Files.copy(source,target, StandardCopyOption.REPLACE_EXISTING);
  5.     }
复制代码

内存映射文件拷贝

  1. public static void main(String[] args) throws IOException {
  2.         try (RandomAccessFile source = new RandomAccessFile("source.txt", "r");
  3.              RandomAccessFile target = new RandomAccessFile("target.txt", "rw")) {
  4.             FileChannel sourceChannel = source.getChannel();
  5.             MappedByteBuffer buffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size());
  6.             target.getChannel().write(buffer);
  7.         }
复制代码

中断线程的三种方式

停止一个线程通常意味着在线程处置惩罚任务完成之前停掉正在做的操作,也就是放弃当前的操作。
在Java中有以下3种方式可以种植正在运行的线程:
1. 使用标志位停止线程(保举)

在run()方法执行完毕后,该线程就停止了,但是在某些特殊情况下,run()方法中会被一直执行,好比在服务端步伐中可能会使用while(true){…}这样的循环结构来不断的接受来自客户端的请求,此时就可以用修改标志位的方式来竣事run 方法。
  1. public class Main {
  2.     private volatile boolean exitFlag = false;
  3.     public void run(){
  4.         while (!exitFlag){
  5.             System.out.println("Thread is running.....");
  6.             try {
  7.                 Thread.sleep(1000);
  8.             }catch (InterruptedException e){
  9.                 System.out.println("Thread interrupted");
  10.                 Thread.currentThread().interrupt();
  11.             }
  12.         }
  13.         System.out.println("Thread exiting.....");
  14.     }
  15.     public void stop(){
  16.         exitFlag = true;
  17.     }
  18.    
  19.     public static void main(String[] args) throws IOException, InterruptedException {
  20.         Main main = new Main();
  21.         Thread thread = new Thread(main::run);
  22.         thread.start();
  23.         Thread.sleep(1000);
  24.         main.stop();
  25.     }
  26. }
复制代码
2. 使用stop()中断线程(不保举)

Thread.stop()方法可以欺凌中断线程的执行,然而,这种方法是不安全的,因为他不能保证线程资源的准确释放和清理,可能导致数据不一致和资源泄露等标题,因此该方法已被官方弃用。
  1. public class Main extends Thread{
  2.     public void run(){
  3.         while (true){
  4.             System.out.println("Thread is running...");
  5.             try {
  6.                 Thread.sleep(1000);
  7.             } catch (InterruptedException e) {
  8.                 Thread.currentThread().interrupt();
  9. //                throw new RuntimeException(e);
  10.             }
  11.         }
  12.     }
  13.     public static void main(String[] args) throws InterruptedException {
  14.         Main main = new Main();
  15.         main.start();
  16.         Thread.sleep(5000);
  17.         main.stop();
  18.     }
  19. }
复制代码
通过JDK的Api,我们会看到java.lang.Thread 范例提供了一系列的方法,如start(),stop(),resume(),suspend(),destory()等方法来管理线程。但是除了start()之外,其他几个方法都被声明为已过时(@Deprecated)。
固然stop()方法确实可以停止一个正在运行的线程,但是这个方法 是不安全的,而且该方法已被弃用,最好不要使用它。
为什么弃用stop():
使用interrupt()中断线程

现在我们知道了使用stop()方式停止线程黑白常不安全的方式,那么我们应该使用什么方法来停止线程呢?答案就是使用interrupt()方法来中断线程。
需要明确的一点是:interrupt()方法并不像在for循环语句中使用break语句那样干脆,立刻就停止循环。调用interrupt()方法仅仅是在当火线程中打一个停止的标记,并不是真的停止线程。
也就是说,线程中断并不会立刻停止线程,而是通知目的线程,有人盼望你停止,至于目的线程收到通知后会如何处置惩罚,则完全由目的线程自行据欸的那个,这一点很重要。如果中断后,线程立刻无条件推出,那么我们又会碰到stop()方法的老标题。
事实上,如果一个线程不能被interrupt,那么stop方法也不会起作用。
接下来我们看一个使用了interrupt()的例子:
  1. public class Main extends Thread{
  2. //    public static void main(String[] args)
  3. //    {
  4. //        SpringApplication.run(Main.class, args);
  5. //    }
  6.     @Override
  7.     public void run() {
  8.         super.run();
  9.         for (int i = 0; i <10000; i++) {
  10.             System.out.println("i="+i);
  11.         }
  12.     }
  13.     public static void main(String[] args)  {
  14.         try {
  15.             Main t = new Main();
  16.             t.start();
  17.             Thread.sleep(1000);
  18.             t.interrupt();
  19.         } catch (InterruptedException e) {
  20.             throw new RuntimeException(e);
  21.         }
  22.     }
  23. }
复制代码
结果如下:
  1. i=9986
  2. i=9987
  3. i=9988
  4. i=9989
  5. i=9990
  6. i=9991
  7. i=9992
  8. i=9993
  9. i=9994
  10. i=9995
  11. i=9996
  12. i=9997
  13. i=9998
  14. i=9999
复制代码
从输出的结果我们会发现interrupt方法并没有停止线程t中的处置惩罚逻辑,也就是说纵然t线程被设置成了中断状态,但是这个中断并不会起作用,那么该如何停止该线程呢?
这就需要使用到别的两个与线程中断有关的方法了
  1. public boolean Thread.isInterrupted() //判断是否被中断
  2. public static boolean Thread.interrupted() //判断是否被中断,并清除当前中断状态
复制代码
这两个方法使得当火线程可以或许感知到是否被中断了(通过查抄标志位)
以是如果盼望线程t 在中断后停止,就必须先判断是否被中断,并为它增加相应的中断处置惩罚代码:
  1. @Override
  2.     public void run() {
  3.         super.run();
  4.         for (int i = 0; i <10000; i++) {
  5.             if (Thread.currentThread().isInterrupted()){
  6.                 //处理中断逻辑
  7.                 break;
  8.             }
  9.             System.out.println("i="+i);
  10.         }
  11.     }
复制代码
在上面这段代码中,我们增加了Thread.isInterrupted()来判断当火线程是否被中断了,如果是,则退出for 循环,竣事线程。
这种方式看起来与之前介绍的“使用标志位中断线程”非常类似,但是碰到了sleep()或者wait()这样的操作,我们只能通过中断来处置惩罚。
  1. public static native sleep(long millis) throws InterrupedExecption
复制代码
Thread.Sleep()方法会抛出一个InterruptedException 异常,当线程被sleep()休眠时 ,如果被中断,就会抛出这个异常。
   注意:Thread.sleep() 方法由于中断额抛出 的异常,是会清除中断标记的

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4