IO体系、集合体系、多线程、jdbc

it2022-05-05  140

 

存储方式:1.顺序结构 2.链式存储

 

1.数据的存储的“容器”:

  ①数组 int[] arr = new int[10]

  ②集合

 

 

Collection:用来存储一个一个的数据

  |-----Set:存储无序的、不可重复的数据--相当于高中的"集合"--“哈希算法”

    |----HashSet:主要的实现类

      |----LinkedHashSet:对于频繁的遍历,效率高

    |----TreeSet:可以按照添加的元素的指定属性进行排序遍历(自然排序Comparable(compareTo(Object obj))&定制排序Comparator(compare(Obejct obj1,Object obj2)))

  |-----List:存储有序的、可以重复的数据--相当于"动态"数组

    |----ArrayList:主要实现类,线程不安全的

    |----LinkedList:对于频繁的插入、删除操作,效率高于ArrayList

    |----Vector:古老的实现类,线程安全的

 

 

 

Map:用来存储一对一对的数据(key-value)

  |----HashMap

    |----LinkedHashMap

  |----TreeMap  

  |----Hashtable

    |----Properties

 

//原则:添加自定义类的对象到Set中时,需要自定义对象所在的类重写:equals()且hashCode();

 

@Test public void test1() throws Exception { RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"), "rw"); // raf.seek(7); // raf.write("xyz".getBytes()); // // raf.close(); //1. raf.seek(7); StringBuffer sb = new StringBuffer(); byte[] b = new byte[20]; int len; while((len = raf.read(b)) != -1){ String str = new String(b,0,len); sb.append(str); } //2. raf.seek(7); raf.write("xyz".getBytes()); raf.write(sb.toString().getBytes()); raf.close(); }

 

class Clerk{//店员 int product; public synchronized void consumeProduct(){//消费产品 if(product <= 0){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ System.out.println(Thread.currentThread().getName() + ":消费了第" + product + "个产品"); product--; notifyAll(); } } public synchronized void addProduct(){//生产产品 if(product >= 20){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ product++; System.out.println(Thread.currentThread().getName() + ":生产了第" + product + "个产品"); notifyAll(); } } }

消费者:

class Comsumer implements Runnable{//消费者 Clerk clerk; public Comsumer(Clerk clerk){ this.clerk = clerk; } @Override public void run() { System.out.println("消费者开始消费产品"); while(true){ try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } clerk.consumeProduct(); } } }

生产者:

class Productor implements Runnable{//生产者 Clerk clerk; public Productor(Clerk clerk){ this.clerk = clerk; } @Override public void run() { System.out.println("生产者开始生产产品"); while(true){ try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } clerk.addProduct(); } } }

测试:

public class TestProduct { public static void main(String[] args) { Clerk clerk = new Clerk(); Productor p1 = new Productor(clerk); Thread t1 = new Thread(p1);//创建了一个生产者 Thread t2 = new Thread(p1); Comsumer c1 = new Comsumer(clerk); Thread tt1 = new Thread(c1);//创建了一个消费者 t1.start(); t2.start(); tt1.start(); } }

 

转载于:https://www.cnblogs.com/lzb0803/p/9201365.html


最新回复(0)