Java学习 11-18

11.面向对象中引用的传递

11.1 引用传递
  • 实例
/*
 * 引用传递
 * 参数之间的传递
 */
class Ref1 {
	int temp = 10;
}
public class RefDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Ref1 r1 = new Ref1();
		r1.temp = 20;
		System.out.println(r1.temp);
		tell(r1);
		System.out.println(r1.temp);
	}
	public static void tell(Ref1 r2) {
		r2.temp = 30;
	}
}

/*
 * 引用传递
 * String 类型的不可变性
 * String 类型里面的数据是不能被更改的
 */
public class RefDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String str1 = "Hello";
		System.out.println(str1);
		tell(str1);
		System.out.println(str1);
	}
	public static void tell(String str2) {
		str2 = "World";
	}
}

/*
 * 引用传递
 * String类型被更改,实质是因为重新分配了内存
 */
class Ref2{
	String str1 = "Hello";
}
public class RefDemo3 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Ref2 r1 = new Ref2();
		r1.str1 = "World";
		System.out.println(r1.str1);
		tell(r1);
		System.out.println(r1.str1);
	}
	public static void tell(Ref2 r2) {
		r2.str1 = "王圣贤";
	}

}
  • 图片说明

在这里插入图片描述

11.2 this关键字
  • 表示类中属性和调用方法
  • 调用本类中的构造方法
  • 表示当前对象
  • 实例
/*
 * this 的作用:
 * 表示本类的属性或方法(上一个Demo介绍)
 * 调用本类中的构造方法(上一个Demo介绍)
 * 表示当前对象
 */
class People1{
	public void tell() {
		System.out.println(this);
	}
}
public class ThisDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		People1 per = new People1();
		System.out.println(per);
		per.tell();
	}

}
11.3 static关键字
  • static声明属性:声明全局属性
  • static声明方法:通过类名调用
  • 注意:使用static方法时,只能访问static声明的属性和方法,而非static声明的属性和方法不能被访问

12 面向对象的抽象类和接口

12.1 final关键字
  • final关键字在java中被称为完结器,表示“最终”
  • final能声明类,方法,属性:
  • 使用final声明的类不能被继承;
  • 使用final声明的方法不能被重写,但可以被重载
  • 使用final声明的变量为常量,且常量不能被修改;
  • 实例:
/*
 * final修饰的类无法被继承
 * final修饰的方法不能被重写
 * final修饰的变量为常量,且无法被修改
 */
class People {      //final修饰的类无法被继承
	public void tell() {      //final修饰的方法不能被重写
		
	}
}
class Student extends People {
	public void tell() {
		
	}
}
public class FinalDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		final String name = "张三";     //final修饰的变量为常量,且无法被修改
		System.out.println(name);
	}

}

12.2 Java抽象类
  • 抽象类:包含一个抽象方法的类为抽象类
  • 抽象方法:声明而未被实现的方法,抽象方法必须使用abstract关键字声明;
  • 抽象类可以被子类继承,但子类必须重写抽象类中所有的抽象方法;
  • 格式:
abstract class className {
	属性;
	方法;
	抽象方法;
}
  • 抽象类不能直接实例化,需要通过子类实例化;
  • 实例:
/*
 * 抽象类:包含一个抽象方法的类
 * 抽象方法:未被实现的方法
 * 抽象类被子类继承,则子类必须重写抽象类的所有抽象方法
 * 抽象类不能直接实例化,需要通过子类实例化
 */
abstract class Abs {                    //抽象类:包含一个抽象方法的类
	private int age;
	public void tell () {
		
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public abstract void say();     //抽象方法:未被实现的方法
}
class Abs1 extends Abs{    //抽象类被子类继承,则子类必须重写抽象类的所有抽象方法
	public void say() {
		System.out.println(getAge());
	}
}
public class AbsDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		//Abs abs = new Abs();      //抽象类不能直接实例化,需要通过子类实例化
		Abs1 a = new Abs1();
		a.setAge(20);
		a.say();
		a.tell();
	}

}

12.3 接口的实现
  • 接口是Java中最重要的概念,接口可以理解为一种特殊的类,里面全部都是由全局变量和公共抽象方法所组成的;
  • 接口的格式
interface interfaceName {
	全局变量;
	抽象方法;
}
  • 接口的实现必须通过子类,使用关键字implements,而且接口是可以多实现的;
  • 一个子类可以同时继承抽象类和实现接口;
  • 一个接口不能继承一个抽象类,但是却可以通过extends关键字继承多个接口,实现接口的多继承;
  • 实例
/*
 * 接口:由全局变量和公共抽象方法组成
 * 接口的实现必须通过子类,使用关键字implements, 而且可以多实现
 * 一个子类可以同时继承抽象类和接口
 */
interface inter {
	public static final int ACG = 100; //全局变量:全局的,不可改变的
	public abstract void tell();
}
interface inter2 {
	public abstract void say();
}
interface inter3 extends inter, inter2 {
	
}
abstract class Abs2 {
	public abstract void print();
}
class A extends Abs2 implements inter, inter2 {
	public void tell() {
		
	}
	public void say() {
		
	}
	public void print() {
		
	}
}
public class interDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		//inter I = new inter();
		A a = new A();
		a.tell();
		a.say();
		a.print();
		System.out.println(inter.ACG);
	}

}

13 字符串

13.1 String字符串
  • 实例化String对象的两种方式;
  • 直接赋值;
  • 使用关键字new;
  • 比较两个字符串是否相等
  • 不可以用“==”,因为这会比较两个字符串的地址;
  • 用“equals”用于比较两个字符串的内容;
  • 实例:
/*
 * String实例化对象有两个方法:直接赋值,使用new关键字
 * String 不可更改性
 */
public class StringDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String str = "Hello";
		String str2 = new String("Hello");    //用new关键字,会创建两个地址
		System.out.println(str == str2);   //"=="用于比较两个地址
		System.out.println(str.equals(str2));   //"equals"用于比较内容
	}

}
  • 图片说明:
    在这里插入图片描述
13.2 String字符串常用方法
  • 长度:length();
  • 字符串转化为数组:toCharArray();
  • 从字符串中取出指定位置的字符:charAt();
  • 字符串与byte数据的转换:getByte();
  • 过滤字符串中存在的字符:indexOf();如果有,则返回当前字符的位置;若无,则返回false;
  • 去掉字符串的前后空格:trim();
  • 从字符串中取出子字符串:subString();
  • 大小写转换:toLower();toUpperCase();
  • 判断字符串的开头结尾字符:endsWith();startWith();
  • 替换String字符串中的一个字符:replace();
  • 实例:
/*
 * String的常用方法
 */
public class StringDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String str = "    asjfsldfjasfsfs";
		
		//length()方法
		System.out.println(str.length());       
		
		//toCharArray()方法
		char c[] = str.toCharArray();           
		for(int i = 0 ; i < c.length; i++) {
			System.out.print(c[i] +"    ");
		}
		System.out.println();
		
		//charAt()方法
		System.out.println(str.charAt(7));      
		
		//getBytes()方法
		byte[] b = str.getBytes();             
		for(int i = 0 ; i < b.length; i++) {
			System.out.print(b[i] +"    ");
		}
		System.out.println();
		
		//indexOf()方法
		System.out.println("f的位置为"+str.indexOf("f"));
		
		//trim()方法
		System.out.println(str.trim());
	}

}

13.3 Java StringBuffer方法
  • StringBuffer:缓冲区,本身也是操作字符串,但是与String不同,StringBuffer是可以被更改的;
  • StringBuffer是一个可操作类,需要实例化进行操作;
  • StringBuffer常用的方法:
  • append();
  • insert();
  • replace();
  • indexOf();
  • Java StringBuilder()的用法
  • StringBuilder是一个可变的字符序列,常用于单线程中;
  • StringBuilder是StringBuffer的一个简易变换,速度更快;
  • 常用的方法: append() , insert();
  • 实例:
/*
 * StringBuffer的介绍及方法
 */
public class StringBufferDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String s = "Hello";
		StringBuffer sb = new StringBuffer();
		sb.append("afjslfsfdsdf");
		tell(s, sb);
		System.out.println(sb);     //StringBuffer 内容可以更改
		System.out.println(s);      //String 内容不可更改
		
		//insert()方法
		sb.insert(0, "wsx, ");
		System.out.println(sb);
		
		//replace()方法
		sb.replace(4, 13, " ");
		System.out.println(sb);
	}
	public static void tell(String s2, StringBuffer sb2) {
		sb2.append("I love you");
		s2 = "jikexueyuan";
	}

}


import java.util.Collections;

public class StringBufferDemo2 {

	private static final String Collection = null;

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
//		String str = "Hello World";
//		for(int i = 0; i < 100; i++) {
//			str = str + i;                         //开辟了100次内存空间,非常好时间
//		}
//		System.out.println(str);
		
		StringBuffer sb = new StringBuffer();
		sb.append("Hello World");
		for(int i = 0; i < 100; i++) {
			sb.append(i);
		}
		System.out.println(sb.toString());
		
	}

}

14 集合类详解

14.1 Connection接口
  • 集合可以理解为一个动态的对象数组,不同的是Collection中的对象内容可以任意的扩充;
  • 优点:性能高,容易扩展和修改;
  • 常用的子类有:List,Set,Queue;在rt->java.util->Collection
14.2 List接口
  • List接口可以存放任意的数据,而且List接口中的内容是可以重复的;
  • List接口常用的子类: ArrayList、Vector;
  • 常用的操作有:
  • 判断集合是否为空: boolean isEmpty();
  • 查找指定对象是否存在:int indexOf(Object O);
  • ArrayList 与 List 的对比:
  • ArrayList是JDK 1.2后推出的,List是JDK 1.0 推出的;
  • ArrayList采用了异步处理,性能高;List采用了同步处理,性能低;
  • ArrayList是非线性安全的,而List是线性安全的;
  • 实例:
import java.util.List;
import java.util.ArrayList;

/*
 * List的常用方法
 * 1.List是一个接口,不能直接实例化,应该需要 子类进行实例化,如 ArrayList, Vector
 * 2.remove(), get(); add(); isEmpty(); indexof();
 */
public class ListDemo {

	public static void main(String[] args) {
		// 实例化
		List<String> lists = null;
		lists = new ArrayList<String>();
		
		//add();
		lists.add("A");
		lists.add("B");
		lists.remove(0);
		lists.add("AB");
		
		//remove();
		lists.remove("AB");
		
		//get(); size();
		for(int i = 0; i < lists.size(); i++) {
			System.out.println(lists.get(i));
		}
		
		//isEmpty();
		System.out.println(lists.isEmpty());
		
		//indexOf();
		System.out.println(lists.indexOf("B"));        //存在,返回当前字符位置
		System.out.println(lists.indexOf("A"));        //不存在,返回-1
	}

}

import java.util.List;
import java.util.Vector;

public class ListDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		List<String> lists = null;
		lists = new Vector<String>();
		lists.add("A");
		lists.add("B");
		
		for(int i = 0; i < lists.size(); i++) {
			System.out.println(lists.get(i));
		}
	}

}

14.3 Set接口
  • Set不能加入重复元素,但是可以排序;
  • Set常用的子类:
  • 散列存放:HashSet;
  • 有序存放:TreeSet;
  • 实例
import java.util.Set;
import java.util.TreeSet;

/*
 * Set的学习
 * 1.Set是一个接口,因此不能直接实例化,使用子类TreeSet, HashSet;
 * 2.Set不能存放重复的元素
 * 3.TreeSet 自动排序; HashSet 散列存放
 */

public class SetDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Set<String> s = new TreeSet<String>();
		s.add("A");
		s.add("B");
		s.add("C");
		s.add("D");
		s.add("G");
		s.add("M");
		s.add("F");
		s.add("J");
		s.add("K");
		System.out.println(s);
	}

}

14.4 Iterator接口
  • 集合输出的标准操作:标准做法是使用Iterator接口;
  • 操作原理:Iterator是专门的迭代输出接口,迭代输出就是将元素一个个进行判断,判断是否与内容,如果有内容则把内容取出来;
  • 在使用迭代输出时,一定不能操作集合中的对象;
  • 实例化如:Iterator iter = lists.iterator();
  • 实例:
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

/*
 * Iterator 接口介绍
 * 1。含有三个方法 : hasNext(); next(); remove();
 * 2.实例化操作:Iterator iter = lists.iterator();
 * 3.在迭代输出时,一定不能使用集合去操作他
 */
public class IterDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		List<String> lists = new ArrayList<String>();
		lists.add("s");
		lists.add("a");
		lists.add("b");
		lists.add("f");
		lists.add("u");
		lists.add("t");
		Iterator<String> iter = lists.iterator();
		while(iter.hasNext()) {
			String str = iter.next();
			if ("a".equals(str) ) {
				iter.remove();
			} else {
				System.out.println(str);
			}
			
		}
	}

}

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

/*
 * Iterator 接口介绍
 * 1。含有三个方法 : hasNext(); next(); remove();
 * 2.实例化操作:Iterator iter = lists.iterator();
 * 3.在迭代输出时,一定不能使用集合去操作他
 */
public class IterDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		List<String> lists = new ArrayList<String>();
		lists.add("s");
		lists.add("a");
		lists.add("b");
		lists.add("f");
		lists.add("u");
		lists.add("t");
		Iterator<String> iter = lists.iterator();
		while(iter.hasNext()) {
			lists.remove(3);         
			/*
			 * 在迭代输出时,一定不能对集合中数据进行处理
			 * 否则,会报错:ConcurrentModificationException
			 */
			System.out.println(iter.next());
		}
	}

}
14.5 Map接口
  • 保存的形式:通常使用key -> value的方式保存
  • 常用的子类
  • HashMap;
  • HashTable;
  • 均为无序存放,且key不能重复;
  • HashMap
  • 原理:先获取插入数据的哈希值,根据哈希值判断应该放入哪个数组元素中;
  • 再对数组元素中的链表进行遍历,若有重复键,则覆盖该键的值;若不冲突,则在链表末尾加入钙元素;
  • 实例:
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/*
 * Map介绍
 * 1.Map含有两个子类:HashMap, HashTable; 
 * 2.方法:containKey(); containValue(); keySet(); values();
 * 3.实例化:Map<Key, Value> map = new HashMap<Key, Value>();
 * 4.Iterator;
 */
public class MapDemo {

	public static void main(String[] args) {
		// Map的实例化操作
		Map<String, String> map = new HashMap<String, String>();
		
		//put();
		map.put("key1", "Hello");
		map.put("key2", "China");
		map.put("key3", "Austualia");
		map.put("key4", "Japan");
		map.put("key5", "USA");
		
		//containKey();
		if (map.containsKey("key1")) {
			System.out.println("key1存在");
		} else {
			System.out.println("key1不存在");
		}
		
		//containValue();
		if (map.containsValue("China")) {
			System.out.println("China存在");
		} else {
			System.out.println("China不存在");
		}
		
		//map.keySet():输出所有的键
		Set<String> s = map.keySet();
		Iterator<String> iter = s.iterator();
		while(iter.hasNext()) {
			System.out.println(iter.next());
			System.out.println();
		}
		
		//map.value();返回的是Collection,输出map的值
		Collection<String> coll = map.values();
		Iterator<String> iter2 = coll.iterator();
		while (iter2.hasNext()) {
			System.out.println(iter2.next());
		}
	}

}

15 面向对象之泛型

15.1 认识泛型
  • 泛型在JDK 1.5之后增加的新功能;
  • 泛型可以解决数据类型的安全性问题;
  • 原理:再累中声明的时候通过一个标识符,表示类中某个属性的类型或是某个方法的返回值以及参数类型;
  • 格式:class 类名 <泛型,泛型> {
  • 对象的创建:
  • 类名<具体类型> 对象名 = new 类名<具体类型> () ;
  • 实例:
/*
 * 认识泛型:
 * 1.示例:经纬度:int, float, double
 * 2.泛型可以解决数据的安全性问题,可以定义希望的类型。
 * 3.定义: class Point<T>;    Point<String> p = new Point<String>();
 * 
 */
class Point<T> {
	private T x;
	private T y;
	public T getX() {
		return x;
	}
	public void setX(T x) {
		this.x = x;
	}
	public T getY() {
		return y;
	}
	public void setY(T y) {
		this.y = y;
	}
	
}

public class GenericDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Point<String> p = new Point<String>();
		p.setX("精度为:100");
		p.setY("纬度为:120");
		System.out.println("X=" + p.getX() + "   Y=" + p.getY());
	}

}
15.2 在构造方法中使用泛型
  • 构造方法:可以为类中属性初始化;
  • 若类中属性通过泛型指定,构造方法不变;
  • 实例:
/*
 * 构造方法中使用泛型
 * 注意:构造方法中使用泛型,并没有发生变化
 */
class Test <T> {      //不能用Test作为类名,未写入类文件。项目可能不一致,如果出现这种情况,则尝试刷新此项目并构建它
	private T value;

	public Test(T value) {
		this.value = value;
	}
	
	public T getValue() {
		return value;
	}

	public void setValue(T value) {
		this.value = value;
	}
}
public class GenericDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Test<String> c = new Test<String>("泛型中使用构造方法");
		System.out.println(c.getValue());
		
	}

}
15.3 设置多个泛型
  • 设置多个泛型直接在<>中添加多个泛型就可以了;
  • 定义:class 类名<泛型,泛型> {
  • - [ ] 实例:
/*
 * 设置多个泛型
 */
class Gen<K,T> {
	private K key;
	private T take;
	public K getKey() {
		return key;
	}
	public void setKey(K key) {
		this.key = key;
	}
	public T getTake() {
		return take;
	}
	public void setTake(T take) {
		this.take = take;
	}
	
}

public class GenericDemo3 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Gen<String, Integer> gen = new Gen<String, Integer>();    //Integer,而非int
		gen.setKey("hello,  ");
		gen.setTake(9527);
		
		System.out.println(gen.getKey() + gen.getTake());
	}

}
15.4 泛型:通配符:?
  • 通配符
  • 可用在主类中的非主方法中,表示未知的类型;
    • 实例:
在这里插入代码片
15.5 泛型接口
  • 在JDK 1.5中,不仅可以声明泛型类,还可以声明泛型接口;
  • 声明泛型接口类似于声明泛型类;
  • 格式:interface 接口名<泛型> {}
  • - [ ] 实例:
class Info<T> { 
	public T key;

	public T getKey() {
		return key;
	}

	public void setKey(T key) {
		this.key = key;
	}

	//通过该方法,可以将地址转化为内容
	public String toString() {
		return this.getKey().toString();
	}
}
public class GenericDemo4 {
	
	public static void main(String[] args) {
		Info<String> i = new Info<String>();
		i.setKey("Hello, world");
		tell(i);
	}
	/*
	 * 通配符:无论什么类型,都可以被执行
	 */
	public static void tell(Info<?> b) {
		System.out.println(b);             //通过toString(),将地址转化为了内容
	}
}

15.6 泛型方法
  • 泛型方法中可以定义泛型参数,此时,泛型参数的类型就是传输数据类型;
  • 格式:
访问权限   <泛型标识>  泛型标识  方法名称([泛型标识], [参数名称])
如 : public <T> T tell(T t) {};
	
  • 实例:
/*
 * 泛型方法
 * 定义: public <T> T tell(T t);
 */
class Gene{
	public <T>T tell(T t) {
		return t;
	}
}
public class GenericDemo6 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Gene g = new Gene();
		String str = g.tell("sfdsfsd");
		System.out.println(str);
		int num = g.tell(42343);
		System.out.println(num);
	}

}
15.7 泛型数组
  • 在使用泛型方法时,也可以传递或返回一个泛型数组;
  • 实例:
/*
 * 定义一个泛型数组
 * 
 */
public class GenericDemo7 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String str[] = {"fefs", "fsdf", "serwe"};
		tell(str);
	}
	public static <T> void tell(T arr[]) {
		for(int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
	
}

16 多线程编程

16.1 线程与进程
  • 线程:程序中单独顺序的控制流
  • 线程本身依靠程序运行;线程是程序中的顺序控制流,只能使用分配给程序的资源与环境;
  • 进程:执行中的程序
  • 一个进程可含多个线程;至少有一个线程;
  • 单线程:主方法就是一个主线程;
  • 多线程:一个程序运行多个任务;更合理的使用CPU;
16.2 线程的实现
  • 线程的两种实现方式:
  • 继承Thread类
  • 和实现Runnable接口
  • Thread 类
  • 在java.lang中定义,继承Thread类,必须重写run()方法;
  • 定义格式:
 class className extends Thread {
 		run() { };
 }
  • 实例:
public class MyThread extends Thread{
	
	private String name;
	
	public MyThread(String name) {
		this.name = name;
	}
	
	public void run() {
		for(int i = 0;  i < 10; i++) {
			System.out.println(this.name + i + "  ");
		}
		super.run();
	}

}


/*
 * 线程的实现
 * 1.通过使用Thread类实现
 * 2.通过使用Runnable接口实现
 */
public class ThreadDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		MyThread t1 = new MyThread("A");
		MyThread t2 = new MyThread("B");
		
		//线程的执行一定不是在主方法中调用run()执行的,这样不会并发执行
//		t1.run();
//		t2.run();
		
		//通过start()才可以并发执行;
		t1.start();
		t2.start();
	}

}
public class MyRunnable implements Runnable{
	
	private String name;
	
	public MyRunnable(String name) {
		this.name = name;
	}
	
	public void run() {
		for(int i = 0;  i < 10; i++) {
			System.out.println(this.name + i);
		}
	}
}


public class ThreadDemo2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		MyRunnable mr1 = new MyRunnable("A");
		MyRunnable mr2 = new MyRunnable("B");
		
		
		//由于Runnable中没有类似start()的方法,因此还是需要调用Thread来实现
		Thread t1 = new Thread(mr1);
		Thread t2 = new Thread (mr2);
		
		
		t1.start();
		t2.start();
	}

}
16.3 线程的状态
  • 线程状态:
  • 创建线程:准备好一个多线程的对象;
  • 就绪状态:调用了start()方法,等待CPU进行调度;
  • 运行状态:执行了run()方法;
  • 阻塞状态:暂时停止执行,可能将资源交给了其他线程;
  • 终止(死亡)状态:线程销毁
  • 实例:
/*
 * 线程的五个方法
 * 1.getName();  currentThread(); isAlive(); join(); sleep(); yield();
 * join(), 强行运行
 * isAlive(),是否已经开始运行
 * sleep(),休眠,通过Thread.sleep()调用;
 * yield(),礼让
 */
class RunnableDemo implements Runnable {
	private String name;
	
	public RunnableDemo (String name) {
		this.name = name;
	}
	
	public void run() {
		for (int i = 0; i < 10; i++) {
			
			if(i == 5) {
				System.out.println("礼让");
				Thread.yield();
			}
			
			try {
				Thread.sleep(1000);             //线程的休眠
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
			//currentThread()方法,与currentThread().getName()方法。
			System.out.println("当前线程对象" + Thread.currentThread() + "  " 
						+"线程名称"+ Thread.currentThread().getName() +"   " + i);
		}
	}
}
public class ThreadDemo3 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		RunnableDemo rd = new RunnableDemo("A");
		RunnableDemo rd2 = new RunnableDemo("B");
		
		Thread t1 = new Thread(rd);
		Thread t2 = new Thread(rd2);
		
		//isAlive()方法
		System.out.println(t1.isAlive());   
		t1.start();
		
		t2.start();
		System.out.println(t1.isAlive());
		
		System.out.println();System.out.println();System.out.println();
		
		
		for (int i = 0 ; i < 20; i++) {
			if(i > 10) {
				try {
					//join(),强行运行
					t1.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println(i);
		}
	}

}

16.4 线程的常用方法
  • 取得线程名称:getName();
  • 取得当前线程对象:currentThread();
  • 判断线程是否启动:isAlive();
  • 现成的强行运行:join();
  • 线程的休眠:sleep();
16.5 线程的优先级
  • 优先级顺序设置
  • 1-MIN_PRIORITY;
  • 10-MAX_PRIORITY;
  • 5-NORM_PRIORITY;
  • 实例
/*
 * 线程优先级的概念
 * 1.Thread.MAXPRIORITY , Thread.MINPRIORITY, Thread.NORMPRIORITY 
 * 2.优先级只是一个可能性,更有可能抢到CPU资源
 */
class Thread4 extends Thread {
	public void run() {
		for(int i = 0; i < 10; i++) {
			try {
				Thread.sleep(1000);
				System.out.println(Thread.currentThread().getName() + "    " + i);
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
		}
	}
}
public class ThreadDemo4 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Thread t1 = new Thread(new Thread4(), "A");
		Thread t2 = new Thread(new Thread4(), "B");
		Thread t3 = new Thread(new Thread4(), "C");
		t1.setPriority(Thread.MAX_PRIORITY);
		t2.setPriority(Thread.MIN_PRIORITY);
		t3.setPriority(Thread.NORM_PRIORITY);
		
		t1.start();
		t2.start();
		t3.start();
	}

}
16.6 同步与死锁
  • 同步代码块:在代码块中加入“synchronized”,则此代码块为同步代码块;
  • 同步代码块格式:synchronized (同步对象) {需要同步的代码块};
  • 同步方法:除代码块可以同步,方法也可以同步;
  • synchronized void 方法名称 {}
  • 死锁:例如,刚毕业的学生期望高薪工作,而公司需要有经验的员工;
  • 实例:

/*
 * synchronized关键字
 * 1.同步代码块
 * 2.同步方法
 */
class MyThreadDemo implements Runnable{
	private int ticket = 5;
	public void run() {
		for(int i = 0; i< 10; i++) {
			tell();
			
			//同步代码块
//			synchronized(this) {
//				
//			}
		}
	}
	
	//同步方法
	public synchronized void tell() {       
		if(ticket > 0) {
			try {
				Thread.sleep(500);
				System.out.println("ticket:" + ticket--);
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
}

/*
 * 死锁:学生找高薪,公司要求有经验
 * 
 */
public class ThreadDemo5 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		
		MyThreadDemo t = new MyThreadDemo();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		Thread t3 = new Thread(t);
		
		t1.start();
		t2.start();
		t3.start();
	}
	
	
}

16.7 线程的声明周期
  • 图片说明
    在这里插入图片描述

17 Java的异常处理

17.1 认识异常
  • 异常是导致程序中断运行的一种指令流
  • 如果不对异常进行正确处理,可能导致程序的中断,从而造成损失;
  • 处理异常:
try {
	异常语句;
}catch (Exception e) {
	...
}finally {
}
17.2 常见的异常
  • 数组越界异常:ArrayIndexxOutOfBoundsException
  • 数字格式化异常:NumberFormatException
  • 算术异常:ArithmeticException
  • 空指针异常:NullPointerException
  • 类型转化异常:ClassCaseException
  • 实例:
/*
 * 异常处理
 * 1.catch 捕获异常,可以捕获多个异常
 * 2.final 一定会执行。
 */
class Exc {
	int a = 10;
	int b = 0;
}
public class ExceptionDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Exc exc = null;
		//exc = new Exc();   //若注释, 空指针异常

		try {
			System.out.println(exc.a / exc.b);
		} catch(NullPointerException e) {
			System.out.println("空指针异常" + e);
		} catch(ArithmeticException e) { 
			System.out.println("算术异常:" + e); //java.lang.ArithmeticException: / by zero
		} finally {
			System.out.println("程序退出");
		}
	}

}

17.3 throws关键词
  • 在定义一个方法的时候,可以使用throws声明;使用throws声明的方法不处理异常,抛给方法的调用者处理;
  • 格式:public void tell() throws Exception {}
  • 实例:
/*
 * throws 关键字
 * 1.不处理异常,抛给方法的调用者
 * 2.若方法的调用者未处理异常,则由JVM处理异常
 */
public class ExceptionDemo2 {

//	1.不处理异常,抛给方法的调用者
//	public static void main(String[] args) {
//		// TODO 自动生成的方法存根
//		try {
//			tell(10,0);
//		} catch(Exception e) {
//			System.out.println(e);
//		}
//	}
	
//	2.若方法的调用者未处理异常,则由JVM处理异常
	public static void main(String [] args) throws Exception {
		tell(10,0);
	}
	
	public static void tell(int i, int j) throws Exception {
		int temp = 0;
		temp = i / j;
		System.out.println(temp);
	}
}

17.4 throw关键词
  • throw抛出一个异常,抛出时直接抛出异常类的实例化对象;
  • 实例
/*
 * throw抛出异常
 * 抛出异常时,直接抛出异常类的实例化对象
 */
public class ExceptionDemo3 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		try {
			throw new Exception("实例化对象");
		} catch(Exception e) {
			System.out.println(e);
		}
	}

}
17.5 自定义异常
  • 自定义异常直接继承Exception就可以完成自定义异常
  • 实例:
class MyException extends Exception {
	public MyException (String msg) {
		super(msg);
	}
}
public class ExceptionDemo4 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		try {
			throw new MyException("自定义异常");
		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

18 本地文件操作

18.1 File简介
  • 实例化:File file = new File(“Hello.txt”);
  • 方法:
  • exist();
  • isFile();
  • isDirectory();
18.2 文件的创建、删除、重命名
  • createNewFile()
  • delete()
  • renameto()
  • 实例:
import java.io.File;
import java.io.IOException;

/*
 * 文件的创建,重命名,删除
 */
public class FileDemo {

	public static void main(String[] args) {
		// 或者"bin/hello.txt';
		/*
		 * 1.默认在文件夹:corejava中
		 * 2.放在子目录中"bin/hello.txt"
		 * 3.创建在上一级目录中:"../hello.txt"
		 * 4.创建在上两级目录中:"../../hello.txt"
		 */
		File file = new File("hello.txt");       //
		
		//文件是否存在
		if(file.exists()) {
			
			//删除文件
			file.delete();
			System.out.println("文件删除成功");
			
			//是否为文件
			System.out.println(file.isDirectory());
			
			//是否文路径
			System.out.println(file.isFile());
		} else {
			System.out.println("文件不存在,创建新的文件");
			try {
				file.createNewFile();
				System.out.println("文件已经成功创建");
				
				//文件的重命名
				File nameto = new File("new Hello.txt");
				file.renameTo(nameto);
				System.out.println("文件重命名成功");
				
			} catch (IOException e) {
				System.out.println(e);
			}
		}
	}

}

import java.io.File;

/*
 * 文件夹的创建,重命名,删除
 */

public class FileDemo2 {

	public static void main(String[] args) {
		// 创建文件夹
		File folder = new File("folder");
		
		if(folder.mkdir()) {
			System.out.println("文件夹创建成功");
		} else {
			System.out.println("文件夹已经存在,创建失败");
		}
		
		//创建多级文件夹
		File newFolder = new File("new folder/one/two");
		
//		if(newFolder.delete()) {
//			System.out.println("删除成功");
//		} else {
//			System.out.println("删除失败");
//		}
		
		//文件夹重命名
		File myNewFolder = new File("new folder/one/2");
		if(newFolder.renameTo(myNewFolder)) {
			System.out.println("文件夹重命名成功");
		} else {
			System.out.println("文件夹重命名失败");
		}
		

			
//		if(newFolder.mkdirs()) {
//			System.out.println("文件夹创建成功");
//		} else {
//			System.out.println("文件夹创建失败");
//			
//		}
	}

}

18.3 文件夹的创建、删除、重命名
  • mkdir()
  • mkdirs()
  • renameto()
  • delete(),文件夹的内容必须为空,才能删除;
18.4 文件属性的读取
  • exists()
  • getName();
  • getPath()
  • getAbsolutePath()
  • length()
  • isHidden()
  • canRead()
  • canWrite()
  • 实例
import java.io.File;
import java.io.IOException;


/*
 * 文件属性的读取:
 * 1.文件是否存在
 * 2.读取文件名称
 * 3.读取文件路径
 * 4.读取文件绝对路径
 * 5.读取文件父级路径
 * 6.读取文件大小
 * 7.判断文件是否被隐藏
 * 8.判断文件是否可读
 * 9.判断文件是否可写
 * 10.判断文件是否为文件夹
 * 
 */
public class FileDemo3 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		File file = new File("hello.txt");
		try {
			file.createNewFile();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
//		 * 1.文件是否存在
		System.out.println(file.exists());
//		 * 2.读取文件名称
		System.out.println(file.getName());
//		 * 3.读取文件路径
		System.out.println(file.getPath());
//		 * 4.读取文件绝对路径
		System.out.println(file.getAbsolutePath());
//		 * 5.读取文件父级路径
		System.out.println(new File(file.getAbsolutePath()).getParent());
//		 * 6.读取文件大小
		System.out.println(file.length()+ "byte");
//		 * 7.判断文件是否被隐藏
		System.out.println(file.isHidden());
//		 * 8.判断文件是否可读
		System.out.println(file.canRead());
//		 * 9.判断文件是否可写
		System.out.println(file.canWrite());
//		 * 10.判断文件是否为文件夹
		System.out.println(file.isDirectory());
	}

}

18.5 文件属性的设置
  • setReadable()
  • setWritable()
  • setReadOnly()
  • 实例
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class ReadFileDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		File file = new File("text.txt");
		if (file.exists()) {
			System.err.println("exist");   //系统输出
			try {
				FileInputStream fis = new FileInputStream(file);
				InputStreamReader isr = new InputStreamReader(fis, "GBK");	
				BufferedReader br = new BufferedReader(isr);
				
				String line;
				while((line=br.readLine()) != null) {
					System.out.println(line);
				}
				
				br.close();
				isr.close();
				fis.close();
				
			} catch (FileNotFoundException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		
		File newfile = new File("newtext.txt"); 
		if(newfile.exists()) {
			System.err.println("exist");  
			
			try {
				FileOutputStream fos = new FileOutputStream(newfile);
				OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");	
				BufferedWriter bw = new BufferedWriter(osw);
				
				
				bw.write("\n长歌行");
				bw.write("\n汉乐府");
				
				bw.close();
				osw.close();
				fos.close();
			} catch (FileNotFoundException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
		}
	}

}

18.6 遍历文件夹
  • 实例
import java.io.File;

/*
 * 遍历文件夹中所有文件
 */
public class ScanerDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		printFiles(new File("B:/work/workspace/corejava"), 0);
	}
	public static void printFiles(File dir, int tab) {
		if (dir.isDirectory()) {
			File[] next = dir.listFiles();
			for (int i = 0 ; i < next.length; i++) {
				for(int j = 0 ; j < tab ; j++) {
					System.out.print("---");
				}
				System.out.println(next[i].getName());
				if(next[i].isDirectory()) {
					printFiles(next[i], tab+1);
				}
			}
		}
	}
}

18.7 文件的简单读写
  • 实例
import java.io.File;
import java.io.IOException;

/*
 * 文件属性的设置
 * 1.设置文件可读
 * 2.设置文件可写
 * 3.设置文件只读
 * 
 */
public class SetFilePropertyDemo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		File fileProperty = new File("fileProperty.txt");
		try {
			if(fileProperty.createNewFile()) {
				System.out.println("文件创建成功");
			} else {
				System.out.println("创建失败");
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		
//		 * 1.设置文件可读
		if(fileProperty.setReadable(false)) {
			System.out.println("不可读设置成功");
		} else {
			System.out.println("设置不成功");
		}
		
//		 * 2.设置文件可写
		fileProperty.setWritable(false);
		
//		 * 3.设置文件只读
		//fileProperty.setReadOnly();
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值