Java 语言程序设计学习笔记
本文含有的主要内容:
- 异常处理与文本I/O
- 抽象类与接口
- Package
- 多线程
本文需要整理的内容还有很多,至少目前来看还只是“学习笔记”风格,内容还较为混乱。
异常处理和文本I/O
异常处理
Java 中的运行时错误会作为异常,这种对象被抛出,而如果抛出的异常没有被处理,程序会非正常终止。
- 异常的类型
- 异常处理模型 declaring -> throwing -> catching
finally 语句
自定义异常类
文件I/O
- 文件类 File
- 写入数据 PrintWriter 类
- 读入数据 Scanner 类
抽象类和接口
- 使用
abstract
关键字 - 接口
- 几种常用的接口
- Comparable
- Cloneable
- Comparable
类的组织——包的概念
编译单元与类空间
- 编译单元:一个 Java 源代码文件
- 一个编译单元中只能有 一个 public 权限的类
- 且该类名与文件名相同
- 类名存在冲突问题
- 编译单元的组成部分
- 所属包的声明;
- Import 包的声明用来导入外部类;
- 类和接口的声明.
包与目录
引入包与静态引入
多线程
如何创建多线程
继承 Thread 类
import java.math.BigDecimal;
import java.math.BigInteger;
public class ThreadTest
{
public static void main(String[] args)
{
System.out.println("Start of the main Thread.");
AnotherThread th1 = new AnotherThread(2000);
AnotherThread th2 = new AnotherThread(5);
th1.start();
th2.start();
System.out.println("End of the main thread.");
}
}
class AnotherThread extends Thread
{
private int num;
public AnotherThread(int num)
{ this.num = num; }
@Override
public void run()
{
BigInteger i = BigInteger.valueOf(num);
BigInteger result = BigInteger.valueOf(1);
System.out.println("A new thread has been created with number " + num);
while (i.compareTo(BigInteger.valueOf(1)) > 0)
{
result = result.multiply(i);
i = i.subtract(BigInteger.valueOf(1));
}
System.out.println("Calc Ans: " + result + " with number " + num);
System.out.println("Thread has ended with number" + num);
}
}
Runnable 接口
线程间的资源共享
当多个线程的执行代码来自于同一个类的run方法时,则称它们共享相同的代码;而当它们访问相同的对象时,则称它们共享相同的数据。
线程间数据共享的实现方法:用一个 Runnable 类型的对象创建多个线程
多线程间的同步控制
改进后的代码: