The advance of Java -- IO, Thread(Day05)


1. IO

①Serialize: When we need to transfer a oject from a computer to another computer's disk, we use serialize. ObjectOutputStream oos

Dog d = new Dog("H",12,"sssssssssss");
		try (
				ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream("d:/a.properties"));
				) {
			
			s.writeObject(d);
			s.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

②Deserialize: ObjectInputStream ois

try (
				ObjectInputStream i = new ObjectInputStream(new FileInputStream("d:/a.properties"));
				)
		{	
			Dog d = (Dog) i.readObject();
			System.out.println(d);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

③Transient: the member variables modified by transient will not participate in the serialize

transient String address;

④writeObject() & readObject()

⑤RandomAccess: program can read and write file freely.

try {
			RandomAccessFile f = new RandomAccessFile("d:/a.properties", "rw");//Read and Write
			f.seek(1);//Insert into '1' position
			f.write("hello ".getBytes());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

2. NIO:

①The difference between IO and NIO: The input and ouput method of traditional IO is blocking. Conversely, NIO will map file or a part of area of file into memory so that it can access file as fast as memory.

②Channel & Buffer:

(1)All the data in NIO need to transferred by Channel, it provide a map method. Traditional input - output is cater to Stream, but NIO is face to block.

(2)All the data need to preserve in Buffer, including the data in Channel.

CharBuffer c = CharBuffer.allocate(8);
		System.out.println("Position " + c.position());the next index can be read.
		System.out.println("limit " + c.limit());// the data behind limit cannot read
		System.out.println("Capacity " + c.capacity());
		c.put("a");
		c.put("b");
		c.put("c");
		System.out.println("Position " + c.position());
		c.flip();//changing the position of 'limit' to 'position', position set '0'
		System.out.println("Position " + c.position());
		System.out.println("limit " + c.limit());
		System.out.println(c.get(1));
		System.out.println("Position " + c.position());
		c.clear();
		System.out.println(c.get(2));
		System.out.println("Position " + c.position());
		System.out.println("limit " + c.limit());
		System.out.println("Capacity " + c.capacity());
	}

3. Thread:

①Process == Application

②Thread is execution unit exist in process. It can only access to resources in this process. When system create a process, it will also create a main thread.

③Thread & Runnable:

Since 'Runnable' is a interface, so we can realize other supclasses and  interfaces easily. But we still need a type of Thread to receive.

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName());
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	

	}

}
public static void main(String[] args) {
		Runnable r = new MyRunnable();
		Thread t = new Thread(r);
		t.start();
	}
④The state of Thread:

⑤Thread.currentThread: gaining current Thread.

for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().isDaemon());
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
		
		Thread t = new Thread(){
			public void run() {		
			System.out.println(Thread.currentThread().getState());
			
		}
		};
		t.start();
⑥Daemon: it will forwardly stop until other thread stop and it should declare before current thread start.

Thread t = new Thread(){
			public void run() {
				try {
					Thread.sleep(1000000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t.setDaemon(true);
		t.start();
		System.out.println(t.getName());
		System.out.println(t.getState());
	}

4. Synchronized: when two thread read a same resources, it will cause  the problem of synchronized.

①Grammar: synchronized(//key object){//method}

public class Test {
	public void t1() {
		synchronized(this){
			try {
				System.out.println("Hot");
				Thread.sleep(10);
				System.out.println("Dog");
				Thread.sleep(10);
				System.out.println("Cat");
				Thread.sleep(10);
				System.out.println();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void t2() {
		synchronized(this){
			try {
				System.out.println("Bao");
				Thread.sleep(10);
				System.out.println("Zi");
				Thread.sleep(10);	
				System.out.println();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
Test t = new Test();
		new Thread() {
			@Override
			public void run() {
				while (true) {
					t.t1();
				}
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				while (true) {
					t.t2();
				}
			}
		}.start();

	}

The question of train tickets:

public class Ticket extends Thread {


	static int count = 100;
	static final Object obj = new Object();


	public void run() {
		while (true) {
			synchronized (obj) {
				if (count > 0) {
					count--;
					System.out.println(
							"Desk " + Thread.currentThread().getName() + " is on sale, and " + "left: " + count);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					System.out.println("Sorry, sold out");
					break;
				}
			}
		}
	}
}
		new Ticket().start();
		new Ticket().start();
		new Ticket().start();
		new Ticket().start();

②DeadLock: when two thread are all wait other release the monitor of synchronized 

Solution: synchronized by order.

String lcs = "left";
		String rcs = "right";
		new Thread() {
			public void run() {
				while (true) {
					synchronized (lcs) {
						System.out
								.println("Picking up the " + lcs + " chopstick and waiting the " + rcs + " chopstick");
						synchronized (rcs) {
							System.out.println(Thread.currentThread() + " is eating");
						}
					}
				}
			}
		}.start();
		new Thread() {
			public void run() {
				while (true) {
					synchronized (rcs) {
						System.out
								.println("Picking up the " + rcs + " chopstick and waiting the " + lcs + " chopstick");
						synchronized (lcs) {
							System.out.println(Thread.currentThread() + " is eating");
						}
					}
				}
			}
		}.start();
	}

③BlockingQueue:

Pattern: Producer & Consumer

BlockingQueue<String> b = new ArrayBlockingQueue<String>(2);

		new Thread() {
			public void run() {
				for (int i = 1; i <= 10; i++) {
					try {
						b.put(i + "");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("The moive has downloaded " + i * 10 + "%");
				}
			}

		}.start();
		new Thread() {
			public void run() {
				for (int i = 1; i <= 10; i++) {

					try {
						System.out.println("The moive has watched " + Integer.valueOf(b.take()) * 10 + "%");
					} catch (NumberFormatException | InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}.start();
	}
④The security of Thread of API & The security of none-Thread of API

Etc:

StringBuffer StringBuilder
      Hashtable HashMap
Vector ArrayList

⑤Thread Pool
Main function:

(1)controlling the number of thread

(2)duplicating thread


Four Thread Pool:

(1)Executors.newCachedThreadPool(): creating thread without limitation, and will destroy when they are not use at a time.

(2)Executors.newFixedThreadPool(int nThreads): creating a thread pool can use the fixed threads.

(3)Executors.newScheduledThreadPool(int corePoolSize): creating a thread pool which can delay or carry out circularly according with the time you set.

(4)Executors.newSingleThreadExecutor(): only create a thread, but when it counter exception, this pool will create another thread replace the old one.

ExecutorService e = Executors.newFixedThreadPool(3);
	Runnable a = new MyRunnable();
	for (int i = 0; i < 10; i++) {
		e.execute(a);
	}
	e.shutdown();
	



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值