JAVA 2022.8.4,8.5课程总结(IO流,线程)

这篇博客详细介绍了JAVA的IO流,包括字节流和字符流的使用,以及缓冲流的应用。同时,讲解了如何进行文件读写操作。此外,文章还探讨了线程的创建,包括通过继承Thread类和实现Runnable接口的方式,为进一步学习线程管理和线程池奠定了基础。
摘要由CSDN通过智能技术生成

一、IO流

        //IO流
        //字节流 byte 1个字节  字节输入流     字节输出流
        //字符流 char 2个字节  字节输入流     字节输出流

1.1字节流 字节缓冲流

        File file=new File("F://easy.txt");
        //字节输入流
        FileInputStream fis=null;
            
        //获取文件对象
        File file=new File("F://easy.txt");
        //字节输入流
        FileInputStream fis=null;
        byte[] arr=new byte[4];
        try {
            //通过文件创建输入流对象
            fis=new FileInputStream(file);

            //字节缓冲输入流
            //BufferedInputStream bis=new  BufferedInputStream(fis);
            //bis.read(arr);
            //字节缓冲输出流:BufferedOutputStream

          int length=-1;

第一种方法:
            do {
                length=fis.read(arr);
                System.out.println(length);
                String str=new String(arr);
                System.out.println(str);
            }while(length!=-1);

第二种方法:

//            while((length=fis.read(arr))!=-1) {
//                String str=new String(arr);
//                System.out.println(str);
//            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

1.2 字符流 字符缓冲流

    File src=new File("F://easy.txt");
        File target=new File("F://target.txt");
        //字符输入流    
        FileReader fr=null;
        //字符输出流
        FileWriter fw=null;
        //字符缓冲输入流
        BufferedReader br=null;
        //字符缓冲输出流
        BufferedWriter bw=null;
        char[] arr=new char[5];
        int length=-1;
        try {
            fr=new FileReader(src);
            fw=new FileWriter(target,true);
            
            br=new BufferedReader(fr);
            String line=br.readLine();
            System.out.println(line);
            
//            while((length=fr.read(arr))!=-1) {
//                fw.write(arr,0,length);
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fr!=null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            if(fw!=null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

1.3 序列化和逆序列化

user类:

import java.io.Serializable;
import java.util.ArrayList;

public class User implements Serializable{
		//private static final long seriaVerSionUID = 234523322l;
		//transient 禁止这个属性被序列化
	transient String name;
	String sex;
	
	//必须实现Serializable可序列化  User对象才能被序列化
	//Demo demo=new Demo();
	
	//ArrayList list=new ArrayList();

	public String toString() {
		return "User [name=" + name + ", sex=" + sex + "]";
	}
}

easy3类:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Easy3 {
	
	public static void main(String[] args) {
		User user=new User();
		user.name="张三";
		user.sex="男";
		
		//列表可序列化,但是里面的对象也需要可序列化 才可以实现整体序列化
		//user.list.add(new Demo());
		FileOutputStream fos=null;
		ObjectOutputStream oos=null;
		try {
			fos=new FileOutputStream("F://target.txt");
			oos=new ObjectOutputStream(fos);
			oos.writeObject(user);
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(oos!=null){
				try {
					oos.flush();
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(fos!=null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

这样就是完成序列化了

把user类属性进行封装

通过easy3类中属性的值写入到文件中

逆序列化:

easy4类:

import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class Easy4 {
	public static void main(String[] args) {
		FileInputStream fis=null;
		ObjectInputStream ois=null;
	try {
		fis=new FileInputStream("f://target.txt");
		ois=new ObjectInputStream(fis);
	Object obj=ois.readObject();
	System.out.println(obj);
	}catch(Exception e) {
		e.printStackTrace();
	}
}
}

把user中属性通过easy3类赋值写入到文件中之后,easy4类就是逆序列化,执行之后会在打印台输出该文件存储的user中属性通过easy3类赋的值

二、线程

2.1 通过继承Thread类创建线程类

public class MyThread extends Thread{
    /**
     * 线程的执行体
     */
    @Override
    public void run() {
        for(int i=0;i<100;i++) {
            System.out.println(Thread.currentThread().getName()+"----"+i);
        }
    }
    public static void main(String[] args) {
        //实例化线程对象
        Thread t1=new MyThread();
        Thread t2=new MyThread();
        //启动方法
        t1.start();
        t2.start();
    }
}

2.2通过实现Runnable接口创建线程类

public class MyRunnable implements Runnable{
	private String str="123456789";
	private int index=0;
	public StringBuffer strB=new StringBuffer();
		public void run(){
			for(int i=0;i<1000;i++) {
				strB.append(1);
			}
//			while(true) {
//				char c=str.charAt(index);
//				index++;
//				System.out.println(Thread.currentThread().getName()+"----"+c);
//				if(index>=str.length()) {
//					break;
//				}
//			}
		}
		public static void main(String[] args) throws InterruptedException {
			//多条线程可以共享runnable中的数据
			//Runnable r1=new MyRunnable();
			MyRunnable r1=new MyRunnable();
			Thread t1=new Thread(r1);
			//设置优先级 1-10 默认是5,越高获得资源几率越大
			t1.setPriority(10);
			Thread t2=new Thread(r1);
			t1.start();
			t2.start();
			Thread.sleep(3000);
			System.out.println(r1.strB.length());
		}

2.3

package com.easy20;

public class Easy {
	
//	static Thread t1=new T1();
//	static Thread t2=new T2();
	public static void main(String[] args) {
//		t1.start();
//		t2.start();
		Thread t1=new T3();
		Thread t2=new T3();
		t1.start();
		t2.start();
	}
	static int i=1;
	//synchronized定义同步的方法  保证线程的安全	
	//public static synchronized void test() {
	//synchronized定义同步代码块,锁对象可以自定义
//	public static  void test() {
//		synchronized (Easy.class) {
//			
//		}
//		System.out.println(i);
//		try {
//			Thread.sleep(1000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		i++;
//	}
	
	//public synchronized void test() {
		
		//synchronized修饰的方法的锁对象是this
		//如果是静态方法是类对象Easy.class
	//}
}
class T3 extends Thread{
	static int i=0;
	synchronized void test() {
		System.out.println(i);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		i++;
	}
	public void run(){
	//	Easy.test();
	}
}
class T1 extends Thread{
	public void run() {
		for(int i=0;i<100;i++) {
			System.out.println(Thread.currentThread().getName()+"----"+i);
			if(i==50) {
//				try {
					//加入--插队的方法join
					//Easy.t2.join();
					//加入--礼让的方法yield
					//Easy.t2.yield();
				//通知线程中止
					Thread.currentThread().interrupt();
				//结束线程
					//Thread.currentThread().stop();
				//判断线程是终止状态
					boolean b=Thread.interrupted();
					System.out.println(b);
//				} 
//				catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				}
		}
	}
}
class T2 extends Thread{
	public void run() {
		try {
			Thread.sleep(1000);
			System.out.println(Thread.currentThread().getName()+"----");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

2.4

package com.easy20;

public class Easy3 {
	static Demo demo=new Demo();
	public static void main(String[] args) {
		T111 t1=new T111();
		T222 t2=new T222();
		t1.start();
		t2.start();
	}
}
class T111 extends Thread{
	@Override
	public void run() {
		Easy3.demo.test1();
	}
}
class T222 extends Thread{
	@Override
	public void run() {
		Easy3.demo.test2();
	}
}
class Demo{
	
	public synchronized void test1() {
		System.out.println("test1");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public synchronized void test2() {
		System.out.println("test2");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

2.5

public class Easy1 {
		public static void main(String[] args) {
			Demo demo=new Demo2();
			//匿名类对象
			Thread t1=new Thread() {
				@Override
				public void run() {
					demo.test1();
				}
			};
			Thread t2=new Thread() {
				@Override
				public void run() {
					demo.test1();
				}
			};
			t1.start();
			t2.start();
		}
}
class Demo{
	public synchronized void test1() {
		System.out.println("test1");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	}
class Demo2 extends Demo{
	//synchronized修饰的方法,重写时synchronized不是强制继承的
	public  void test1(){
		System.out.println("test2");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	}

2.6

package com.easy21;

public class Easy2 {
	
	public static void main(String[] args) {
		Demo22 demo=new Demo22();
		Thread t1=new Thread() {
			@Override
			public void run() {
				Demo22.test();
			}
		};
		Thread t2=new Thread() {
			@Override
			public void run() {
				demo.test2();
			};
		};
		t1.start();
		t2.start();
	}
}
class Demo22{
	static synchronized void test() {
		System.out.println("test");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	synchronized void test2() {
		System.out.println("test2");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

2.7线程池

package com.easy21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Easy3 {
	//线程池
	public static void main(String[] args) {
		newCachedThreadPool();
	}
	public static void newCachedThreadPool() {
		//实例化线程池对象
		ExecutorService ex=Executors.newCachedThreadPool();
		Runnable r=new Runnable() {
			public void run() {
				System.out.println(Thread.currentThread().getName()+"----");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		for(int i=0;i<10;i++) {
			ex.execute(r);
				try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

2.8 线程池的数量

package com.easy21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Easy4 {
	
	public static void main(String[] args) {
		newFixedThreadPool();
	}
	//创建固定线程池中线程的数量
	public static void newFixedThreadPool() {
		ExecutorService es=Executors.newFixedThreadPool(5);
		Runnable r=new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName()+"------");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		for(int i=0;i<10;i++) {
			es.execute(r);
		}
	}
}

2.9

package com.easy21;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Easy5 {
		public static void main(String[] args) throws InterruptedException, ExecutionException {
			ExecutorService es=new ThreadPoolExecutor(2,4,60L,TimeUnit.MILLISECONDS,new SynchronousQueue<Runnable>(),
											Executors.defaultThreadFactory(),new Easy5.MyRejectedExecutionHandler());
				Runnable r=new Runnable() {
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName()+"------");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
//		for(int i=0;i<10;i++) {
//			es.execute(r);
//		}
		Callable call=new MyCall();
		//for(int i=0;i<5;i++) {
			Future fut=es.submit(call);
			Object obj=fut.get();
			boolean b=fut.cancel(true);
			System.out.println(b);
			System.out.println(obj);
		//}
}
		static class MyRejectedExecutionHandler implements RejectedExecutionHandler{
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			int size=executor.getQueue().size();
			System.out.println(size);
		}	
	}
}
class MyCall implements Callable<String>{
	@Override
	public String call() throws Exception {
		System.out.println("--------线程开始");
		String str="nihao";
		Thread.sleep(3000);
		return str;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值