八、多线程
1.进程: 在内存中开辟了一块空间,供程序运行。一个进程表示一个程序的运行。
一个程序可以开多个进程。
2.线程:是程序运行中最小的单位。一个进程可以有多个线程,但至少有一个线程。
进程中执行运算的最小单位,可完成一个独立的顺序控制流程
3.实现多线程的两种方式:
1,写一个类 继承Thread
重写run();方法
通过start();启动线程
如果调用run方法,那么就只有一个main线程
2,实现 Runable接口
重写run();方法
通过代理模式运行start();启动线程
4.设置线程运行的优先级1-10 :setPriority(10) Thread.MAX_PRIORITY Thread.MIN_PRIORITY
优先级高的线程会获得更多的运行机会。
5.synchronized:同步锁 :当多个线程对象操纵同一资,源时,要使用synchronized关键字来进行资,源的
的同步处理,可以使用同步方法和同步代码块来实现。
6.StringBuffer 线程安全 效率低
StringBuilder 线程不安全 效率高
HashTable 线程安全 效率低
HashMap 线程不安全 效率高
7.线程睡眠:sleep()方法使线程转到阻塞状态
8.线程强制运行:join()方法使当前线程暂停执行,等待调用该方法的线程结束后再继续执行本线程。
9.线程礼让:yield()方法、暂停当前正在执行的线程对象,把执行机会让给相同的或者更高优先级的线程。
九、File和IO流
1、File:
2.File类常用的方法
3.代码演示
package jbit.io;
import java.io.*;
public class FileMethods {
public static void main(String[] args) {
FileMethods2 fm=new FileMethods2();
File file=null;
file=new File("D:\myDoc\test.txt");
//fm.create(file);
fm.showFileInfo(file);
//fm.delete(file);
}
/**
* 创建文件的方法
* @param file 文件对象
*/
public void create(File file){
if(!file.exists()){
try {
file.createNewFile();
System.out.println("文件已创建!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 删除文件
* @param file 文件对象
*/
public void delete(File file){
if(file.exists()){
file.delete();
System.out.println("文件已删除!");
}
}
/**
* 显示文件信息
* @param file 文件对象
*/
public void showFileInfo(File file){
if(file.exists()){ //判断文件是否存在
if(file.isFile()){ //如果是文件
System.out.println("名称:" + file .getName());
System.out.println("相对路径: " + file.getPath());
System.out.println("绝对路径: " + file.getAbsolutePath());
System.out.println("文件大小:" + file.length()+ " 字节");
}
if(file.isDirectory()){
System.out.println("此文件是目录");
}
}else
System.out.println("文件不存在");
}
}
4.java流的分类
5.文本文件的读写
用FileInputStream和FileOutputStream读写文本文件
用BufferedReader和BufferedWriter读写文本文件
6.二进制文件的读写
使用DataInputStream和DataOutputStream读写二进制文件
7.InputStream类常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
int available()
子类FileInputStream常用的构造方法
FileInputStream(File file)
FileInputStream(String name)
8.OutputStream类常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子类FileOutputStream常用的构造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
9.Writer类常用方法
write(String str)
write(String str,int off,int len)
void close()
void flush()
子类BufferedWriter常用的构造方法
BufferedReader(Writer out)