大概每一个人在学生时代开始就使用Java了,咱们一直在学习Java,但Java中总有一些概念含混不清,不管是对初级仍是高级程序员都是如此。因此,这篇文章的目的就是弄清楚这些概念。java
读完本文你会对这些概念有更深刻的了解,还能弄清楚一切灰色的东西。在本书中,咱们将讨论匿名内联类、多线程、同步和序列化。程序员
Java匿名类很像局部类或内联类,只是没有名字。咱们能够利用匿名类,同时定义并实例化一个类。只有局部类仅被使用一次时才应该这么作。面试
匿名类不能有显式定义的构造函数。相反,每一个匿名类都隐含地定义了一个匿名构造函数。后端
建立匿名类有两种方法:微信
理解代码的最好方法就是先阅读,因此咱们首先来看看代码。网络
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并列的顶层类。多线程
Football能够是抽象类,请看下面的代码。架构
public abstract class Football { abstract void kick(); }
匿名类不只能够是抽象类,还能够是具体类。ide
// normal or concrete class public class Football { public void kick(){} }// end of class scope.
若是Football类没有不带参数的构造方法怎么办?咱们能够在匿名类中访问类变量吗?咱们须要在匿名类中重载全部方法吗?函数
// 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.
匿名类的用途:
button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // your handler code here } });
咱们建立了一个匿名类,实现了setOnClickListener接口。当用户点击按钮时会触发它的onClick方法。
Java中的多线程可以同时执行多个线程。线程是轻量级的子进程,也是处理的最小单位。使用多线程的主要目的是最大化CPU的使用率。咱们使用多线程而不是多进程,由于线程更轻量化,也能够共享同一个进程内的内存空间。多线程用来实现多任务。
线程的生命周期
如上图所示,线程的生命周期主要有5个状态。咱们来依次解释每一个状态。
为何使用多线程?
使用线程可让Java应用程序同时作多件事情,从而加快运行速度。用技术术语来讲,线程能够帮你在Java程序中实现并行操做。因为现代CPU很是快,还可能包含多个核心,所以仅有一个线程就没办法使用全部的核心。
须要记住的要点
多线程能够更好地利用CPU。
提升响应性,提升用户体验
减小响应时间
同时为多个客户端提供服务
建立线程的方法主要有两种:
扩展Thread类
实现Runnable接口
经过扩展Thread类来建立线程
建立一个类扩展Thread类。该类应当重载Thread类中的run()方法。线程在run()方法中开始生命周期。咱们建立新类的对象,而后调用start()方法开始执行线程。在Thread对象中,start()会调用run()。
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(); } } }
下面的代码建立了一个类,实现java.lang.Runnable接口并重载了run()方法。而后咱们实例化一个Thread对象,调用该对象的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(); } } }
关注微信公众号:Java技术栈,在后台回复:多线程,能够获取我整理的 N 篇最新多线程教程,都是干货。
Thread类与Runnable接口
扩展Thread类,就没法扩展更多的类,由于Java不容许多重继承。多重继承能够经过接口实现。因此最好是使用接口而不是Thread类。
若是扩展Thread类,那么它还包含了一些方法,如yield()、interrupt()等,咱们的程序可能用不到。而在Runnable接口中就没有这些排不上用场的方法。
同步指的是多线程的同步。synchronized的代码块在同一时刻只能被一个线程执行。Java中的同步是个很重要的概念,由于Java是多线程语言,多个线程能够并行执行。在多线程环境中,Java对象的同步,或者说Java类的同步很是重要。
为何要同步?
若是代码在多线程环境下执行,那么在多个线程中共享的对象之间须要同步,以免破坏状态,或者形成任何不可预料的行为。
在深刻同步的概念以前先来理解一下这个问题。
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(); } }
给printTable()方法加上synchronized,那么synchronized的方法在执行结束以前不会让其余线程进入。下面的输出结果就很是稳定了。
输出:
5 10 15 20 25 100 200 300 400 500
相似地,Java的类和对象也能够同步。
注意:咱们并不必定须要同步整个方法。有时候最好是仅同步方法的一小部分。Java的synchronized代码段能够实现这一点。
Java中的序列化是一种机制,能够将对象的状态写入到字节流中。相反的操做叫作反序列化,将字节流转换成对象。
序列化和反序列化的过程是平台无关的,也就是说,在一个平台上序列化对象,而后能够在另外一个平台上反序列化。
序列化时调用ObjectOutputStream的writeObject()方法,反序列化调用ObjectInputStream类的readObject()方法。
下图中,Java对象被转换成字节流,而后存储在各类形式的存储中,这个过程叫作序列化。图右侧,内存中的字节流转换成Java对象,这个过程叫做反序列化。
显然,建立的Java类在程序执行结束或停止后,对象就销毁了。为了不这个问题,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
须要记住的重点
一、首先咱们解释了匿名类,以及用途和使用方法。
二、其次咱们讨论了Java中的多线程,线程的生命周期,以及用途。
三、同步只容许一个线程进入同步的方法或代码块去访问资源,其余线程必须在队列中等待。
四、序列化就是存储对象状态供之后使用的过程。
做者:Himanshu Verma
原文: https://medium.com/swlh/4-thi...
译者:弯月,责编:屠敏,出品:CSDN(ID:CSDNnews)
推荐去个人博客阅读更多:
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
以为不错,别忘了点赞+转发哦!