读完本文你会对这些概念有更深入的了解,还能弄清楚一切灰色的东西。在本书中,我们将讨论匿名内联类、多线程、同步和序列化。
1: 匿名类
扩展已有的类(可以是抽象类,也可以是具体类)
创建接口
interface Football
{
void kick();
}
class AnnonymousClass {
public static Football football = new Football() {
@Override
public void kick() {
System.out.println("Nested Anonymous Class.");
}
};
public static void main(String[] args)
{
// anomynous class inside the method
Football footballObject = new Football()
{
@Override
public void kick()
{
System.out.println("Anonymous Class");
}
};
footballObject.kick();
AnnonymousClass.football.kick();
}
}
匿名类可以在类和函数代码块中创建。你也许知道,匿名类可以用接口来创建,也可以通过扩展抽象或具体的类来创建。上例中我先创建了一个接口Football,然后在类的作用域和main()方法内实现了匿名类。Football也可以是抽象类,也可以是与interface并列的顶层类。
public abstract class Football
{
abstract void kick();
}
// normal or concrete class
public class Football
{ public void kick(){}
}// end of class scope.
// normal or concrete class
public class Football {
protected int score;
public Football(int score)
{
this.score = score;
}
public void score(){
System.out.println("Score "+score);
};
public void kick(){}
public static void main(String[] args) {
Football football = new Football(7)
{
@Override
public void score() {
System.out.println("Anonymous class inside the method "+score);
}
};
football.score();
}
}
// end of class scope.
创建匿名类时可以使用任何构造方法。注意这里也使用了构造方法的参数。
匿名类可以扩展顶层类,并实现抽象类或接口。所以,访问控制的规则依然适用。我们可以访问protected变量,而改成private就不能访问了。
由于上述代码中扩展了Football类,我们不需要重载所有方法。但是,如果它是个接口或抽象类,那么必须为所有未实现的方法提供实现。
匿名类中不能定义静态初始化方法或成员接口。
匿名类可以有静态成员变量,但它们必须是常量。
更清晰的项目结构:通常我们在需要随时改变某个类的某些方法的实现时使用匿名类。这样做就不需要在项目中添加新的*.java文件来定义顶层类了。特别是在顶层类只被使用一次时,这种方法非常好用。
UI事件监听器:在图形界面的应用程序中,匿名类最常见的用途就是创建各种事件处理器。例如,下述代码:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your handler code here
}
});
2:多线程

New:创建线程的实例后,它会进入new状态,这是第一个状态,但线程还没有准备好运行。
Runanble:调用线程类的start()方法,状态就会从new变成Runnable,意味着线程可以运行了,但实际上什么时候开始运行,取决于Java线程调度器,因为调度器可能在忙着执行其他线程。线程调度器会以FIFO(先进先出)的方式从线程池中挑选一个线程。
Blocked:有很多情况会导致线程变成blocked状态,如等待I/O操作、等待网络连接等。此外,优先级较高的线程可以将当前运行的线程变成blocked状态。
Waiting:线程可以调用wait()进入waiting状态。当其他线程调用notify()时,它将回到runnable状态。
Terminated:start()方法退出时,线程进入terminated状态。
扩展Thread类
public class MultithreadingTest extends Thread
{
public void run()
{
try{
System.out.println("Thread "+Thread.currentThread().getName()+" is now running");
}catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
MultithreadingTest multithreadingTest = new MultithreadingTest();
multithreadingTest.start();
}
}
}
public class MultithreadingTest implements Runnable
{
@Override
public void run() {
System.out.println("Thread "+Thread.currentThread().getName()+" is now running"); //To change body of generated methods, choose Tools | Templates.
}
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
Thread thread = new Thread(new MultithreadingTest());
thread.start();
}
}
}
扩展Thread类,就无法扩展更多的类,因为Java不允许多重继承。多重继承可以通过接口实现。所以最好是使用接口而不是Thread类。
如果扩展Thread类,那么它还包含了一些方法,如yield()、interrupt()等,我们的程序可能用不到。而在Runnable接口中就没有这些排不上用场的方法。
class Table {
void printTable(int n) {//method not synchronized
for (int i = 1; i <= 5; i++) {
System.out.print(n * i+" ");
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
public void run() {
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
public void run() {
t.printTable(100);
}
}
class TestSynchronization1 {
public static void main(String args[]) {
Table obj = new Table();//only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
100 5 200 10 300 15 20 400 500 25
class Table {
synchronized void printTable(int n) {//synchronized method
for (int i = 1; i <= 5; i++) {
System.out.print(n * i+" ");
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
class TestSynchronization3 {
public static void main(String args[]) {
final Table obj = new Table();//only one object
Thread t1 = new Thread() {
public void run() {
obj.printTable(5);
}
};
Thread t2 = new Thread() {
public void run() {
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
5 10 15 20 25 100 200 300 400 500
4:序列化
Java中的序列化是一种机制,可以将对象的状态写入到字节流中。相反的操作叫做反序列化,将字节流转换成对象。

public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String serializeValueName;
private transient int nonSerializeValueSalary;
public String getSerializeValueName() {
return serializeValueName;
}
public void setSerializeValueName(String serializeValueName) {
this.serializeValueName = serializeValueName;
}
public int getNonSerializeValueSalary() {
return nonSerializeValueSalary;
}
public void setNonSerializeValueSalary(int nonSerializeValueSalary) {
this.nonSerializeValueSalary = nonSerializeValueSalary;
}
@Override
public String toString() {
return "Employee [serializeValueName=" + serializeValueName + "]";
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializingObject {
public static void main(String[] args) {
Employee employeeOutput = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;
employeeOutput = new Employee();
employeeOutput.setSerializeValueName("Aman");
employeeOutput.setNonSerializeValueSalary(50000);
try {
fos = new FileOutputStream("Employee.ser");
oos = new ObjectOutputStream(fos);
oos.writeObject(employeeOutput);
System.out.println("Serialized data is saved in Employee.ser file");
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Serialized data is saved in Employee.ser file.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerializingObject {
public static void main(String[] args) {
Employee employeeInput = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("Employee.ser");
ois = new ObjectInputStream(fis);
employeeInput = (Employee)ois.readObject();
System.out.println("Serialized data is restored from Employee.ser file");
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Name of employee is : " + employeeInput.getSerializeValueName());
System.out.println("Salary of employee is : " + employeeInput.getNonSerializeValueSalary());
}
}
Serialized data is restored from Employee.ser file
Name of employee is : Aman
Salary of employee is : 0
如果父类实现了Serializable接口,那么子类就不需要实现了,但反过来不一定成立。
只有非静态数据成员可以在序列化过程中保存下来。
静态数据成员和临时数据成员不会在序列化过程中保存下来。所以,如果不想保存某个非静态数据成员,则可以将其设置为transient。
反序列化过程中不会调用对象的构造函数。
关联对象必须实现Serializable接口。
总结
1、首先我们解释了匿名类,以及用途和使用方法。
2、其次我们讨论了Java中的多线程,线程的生命周期,以及用途。
3、同步只允许一个线程进入同步的方法或代码块去访问资源,其他线程必须在队列中等待。
4、序列化就是存储对象状态供以后使用的过程。
全部评论