Java Study Notes (Day 6)

The Java language uses multithreading to implement multiple tasks in a program running at the same time. Among threads running and processes, processes are various applications that the operating system runs. A process can contain one or more threads, and a thread is a branch of the execution part of the program. Using multithreading can open up another execution branch to complete these time-consuming operations, and as a branch, that is, the current main thread can continue to execute other business codes.

Thread has a life cycle, which contains 3 states, namely birth state, ready state and running state. The birth state is the state that the user is in when the thread is created. The thread is in the birth state before the user uses the thread instance to call the start() method; after the user calls the start() method, the thread program is in the ready state (also known as the available state). Execution state), when the thread gets system resources, it enters the running state.

Once the thread enters the executable state, it will be tossed between the ready and executing states, and it may also enter the waiting, sleeping, blocking or dying state. When the thread in the running state calls the wait() method in the Thread class, the thread is in the waiting state. The thread entering the waiting state must call the notify() method of the Thread class to be woken up, and the notifyAll() method is to call all the The thread in the waiting state wakes up; when the thread calls the sleep() method in a Thread class, the thread enters the sleep state; if a thread issues an input/output request in the running state, the thread will enter the blocking state and wait in its When the input/output ends, the thread enters the ready state. For a blocked thread, even if the system resources are idle, the thread still cannot return to the execution state; when the thread's run() method is executed, the thread enters the dead state.

Although multithreading looks like simultaneous execution, in fact, only one thread is executed at the same time point, but the switching between threads is faster, so it will give the illusion of simultaneous execution of threads. In the Windows operating system, the system allocates a small CPU time slice to each thread, and when the CPU time expires, the current thread is replaced with the next thread, even if the thread has not ended.

There are several possibilities to make the line program in the ready state: calling the sleep() method, calling the wait() method, and waiting for the input/output to complete. When the thread is in the ready state, there are several ways to make the thread enter the executable state again: the thread calls the notify() method, the thread calls the notifyAll() method, the thread calls the interrupt() method, the thread sleep time ends, input/output end.

The main method in Java is actually the entry point to start the main thread. The currentThread() method in the Thread class can get the current thread and output the name of the thread.

The Thread class is the thread class of the Java language, which is located in the java.lang package. The instance object of this class is a thread object, so integrating this class to write a thread subclass is one of the ways to achieve multithreading. The start() method of the Thread class is used to start a thread object. Starting a thread multiple times, or starting an already running thread object is illegal and will throw an IllegalThreadStateException exception object. The static method sleep() of the Thread class is used to sleep the current thread for the specified number of milliseconds.

If you use the method of inheriting the Thread class to write a thread class, other parent classes cannot be inherited. The Java language provides the Runnable interface, which can also be implemented after inheriting other classes to achieve the purpose of creating threads. The Runnable() interface also defines the run() method. When implementing this interface, you must implement the run() method in the interface.

The object that implements the Runnable interface needs to be passed to the constructor of the Thread class, and the thread class is created through the Thread constructor, that is to say, the implementation object of the Runnable interface needs to be passed to the instance object of the Thread class to start the thread. There are many constructors in the Thread class. The commonly used constructors for receiving Runnable interface parameters are as follows:

MouseListener listener method description
method illustrate
Thread(Runnable target) Create a thread object using the Runnable interface implementation object
Thread(Runnable target, String name) Create a thread object using the Runnable interface implementation object and specify the name of the thread

The steps to start a new thread using the Runnable interface are as follows: (1) Create an instance object of the Runnable interface; (2) Create a Thread instance object with the Runnable interface instance object; (3) Call the start() method of the Thread thread object to start the thread.

To start a new thread, instead of calling the run() method of the Thread subclass object directly, call the start() method of the Thread subclass. The start() method of the Thread class spawns a new thread that runs the run() method of the Thread subclass.

One way to control thread suspension is to use the sleep() method. The sleep() method requires a parameter to specify the time, in milliseconds, that the thread sleeps (that is, paused). It is usually used in the loop body of the run() method. Use a boolean flag in the run() method to control the stopping of the loop. If the thread enters the ready state by using the sleep() or wait() method, you can use the interrupt() method in the Thread class to make the thread leave the run() method and end the thread at the same time, but the program will throw an InterruptedException. When a thread joins another thread using the join() method, the other thread will wait for the thread to finish executing before continuing.

Each thread has its own priority. The priority of the thread can indicate the importance of the thread in the program. If there are many threads in the ready state, the system will decide which thread to use first to enter the running state according to the priority. The member variables contained in the Thread class represent the priority of the thread, such as Thread.MIN_PRIORITY (constant 1), Thread.MAX_PRIORITY (constant 10), Thread.NORM_PRIORITY (constant 5), where each Java priority is in Thread. Between MIN_PRIORITY~Thread.MAX_PRIORITY, by default, the priority of each thread is Thread.NORM_PRIORITY, and each newly generated thread inherits the priority of the parent thread. The priority of the thread can be adjusted using the setPriority method. If the priority is not set within 1~10 using this method, an IllegalArgumentException will be generated.

How to solve the problem of resource sharing? Basically, all methods to solve the problem of multi-threaded resource conflict are to allow only one thread to access the shared resource within a specified period of time, which requires a lock on the shared resource. (1) Synchronization block, the synchronization mechanism provided in Java can effectively prevent resource conflicts, and the synchronization mechanism uses the synchronized keyword. Usually, the operation of shared resources is placed in the code block defined by synchronized, so that when other threads also acquire the lock, they must wait for the object lock of the code block to be released before entering this area. (2) The synchronized method is to modify the synchronized keyword in front of the method. When an object calls the synchronized method, other methods must wait for the synchronized method to be executed before it can be executed.

Swing programs use a single-threaded mechanism for interface drawing and practical processing. In Java, Swing event processing threads are defined by the EventQueue class. EventQueue is a platform-independent class that queues events from underlying classes and trusted application classes. This class provides two methods to execute other threads in the event queue: the invokeLater method and the invokeAndWait method. The invokeLater method will call the run method in the specified Runnable interface implementation object, and execute the business logic in the method. These business logic will be executed asynchronously, that is, the run() method will be executed asynchronously, so that the Swing interface processing and business processing can be performed at the same time. Does not affect the program interface. The invokeAndWait method will also call the run method in the specified Runnable interface implementation object, and execute the business logic in the method. The difference is that the invokeAndWait() method will wait for the run() method of the Runable object to be executed before returning to the method caller. These business logic will be executed asynchronously, that is, the run() method will be executed asynchronously. Throws exceptions: InterruptedException and InvocationTargetException. These two methods are static methods, which can be called directly through the class name without creating an object.

GUI event processing mechanism is the key technology for building interactive applications, in which events are various operations performed by users on the program interface, and the business processing of various events is completed by corresponding listeners. Each component is a subclass of the java.awt.Component class, and they all inherit the methods of the Component class. The addKeyListener() method is used to register a listener for key events with the component. When the user presses the button on the keyboard on the component When the key is pressed, an event object of type KeyEvent will be generated, which will be captured by the listener registered on the component and processed by the method specified by the listener.

The so-called events are various situations that may occur during the running of the program. Events are also objects in the Java language, and they are either direct subclasses or indirect subclasses of the java.awt.AwtEvent class. The AWTEvent class inherits from the EventObject class. The functions and generation conditions of commonly used AWT event classes are as follows:

AWT event class description
event class illustrate
ActionEvent Action event, which is generated when the user clicks a button, selects a menu, a list, etc.
AdjustmentEvent Adjust the event, which is generated when the scroll bar changes
ComponentEvent Component events, which are generated when components are hidden, shown, moved, etc.
ContainerEvent Container component, this event is generated when the container changes, such as adding a component to the container
FocusEvent Focus event, which is fired when the component gains and loses focus
HierarchyEvent Hierarchical events, which fire events when the component level changes
InputMethodEvent Input method event, an event triggered when the input method changes
ItemEvent Option event, an event triggered when the data of the checkbox component, checkbox menu item, list, drop-down selection box and other components changes
KeyEvent

key event, an event fired when a keyboard key is pressed or raised

MouseEvent Mouse events, events that are triggered when the mouse state is changed, such as clicking a mouse button
MouseWheelEvent Mouse wheel event, an event fired when the mouse wheel is scrolled
PaintEvent Drawing event, triggered when a drawing event occurs
TextEvent Text event, which is fired when the content of the textbox and textfield components changes
WindowsEvent 窗口事件,当窗体被打开、关闭、最小化、最大化、还原和激活时触发的事件

事件监听器用于监听指定的事件类型,它们是Swing定义的不同的接口的实现对象。各种类型的组件都可以产生不同的事件对象,这些事件对象由指定的监听器捕获,并调用指定事件类型的处理方法来处理事件。有的事件监听器接口中定义了多个方法,在实现这样的监听器接口时就必须实现接口中的所有方法。

适配器是事件监听接口的实现类,这些实现类实现了相应的事件监听器接口,并为接口中的所有方法定义了空的实现方法,也就是声明了接口中定义的所有方法,但是方法体是空的。在定义自己的事件监听器时,继承相应的适配器类,然后重新需要的事件方法即可。由于适配器中提供的都是监听器接口的空方法实现,实例化适配器的实例对象没有任何意义,所有适配器被定义为abstract抽象类,但是其中的事件方法都不是抽象的。这样可以有选择地重写这些指定方法。每个方法的声明格式都带有空的{}花括号,即空方法体。在重写某个方法时,要在方法体中编写指定的事件处理代码。

执行System类的exit()方法退出当前Java程序和使用EXIT_ON_CLOSE方式通过关闭按钮关闭窗体是不一样的,后者只是关闭窗体(如果当前窗体是程序的一个模块,那么不会影响到程序的继续执行),而前者将退出这个程序。

鼠标事件监听器由MouseListener接口和MouseMotionListener接口定义,它们分别定义了捕获不同鼠标操作的方法:

MouseListener监听器方法说明
方法 说明
mouseClicked(MouseEvent e) 处理鼠标单击事件的方法
mouseEntered(MouseEvent e) 鼠标进入组件区域中执行的方法
mouseExited(MouseEvent e) 鼠标离开组件区域时执行的方法
mousePressed(MouseEvent e) 按下鼠标按键时执行的方法
mouseReleased(MouseEvent e) 释放鼠标按键时执行的方法
MouseMotionListener监听器方法的说明
方法 说明
mouseMoved(MouseEvent e) 处理鼠标移动事件的方法
mouseDragged(MouseEvent e) 处理鼠标拖动事件的方法
MouseEvent类常用方法说明
方法 说明
getButton() 返回更改了状态的鼠标按键(如果有)
getClickCount() 返回与此事件关联的鼠标单击次数
getLocationOnScreen() 返回鼠标相对于屏幕的绝对x,y左边
getPoint() 返回事件相对于源组件的x,y坐标
translatePoint(int x,int y) 通过将事件坐标加上指定的x(水平)和y(垂直)偏移量,将事件的坐标平移到新位置

键盘事件监听器由KeyListener接口定义,编写键盘事件监听器必须实现该接口中的3个方法,这3个方法分别处理不同的按键事件:

KeyListener事件监听器方法说明
方法 说明
keyPressed(KeyEvent e) 按下某个按键时调用此方法
keyReleased(KeyEvent e) 释放某个按键时调用此方法
keyTyped(KeyEvent e) 输入某个按键时调用此方法

对于键盘事件监听器的适配器是KeyAdapter类,可以继承该类,然后重写需要的单个方法;如果需要处理所有键盘事件的监听,那么干脆实现KeyListener接口,总之需要根据程序需求选择实现KeyListener接口或继承KeyAdapter抽象类。

KeyListener事件监听器方法说明
方法 返回值类型 说明
getKeyChar() char 返回与此事件中的键关联的字符
getKeyCode() int 返回与此事件中的键关联的整数keyCode
getKeyModifiers(int modifiers) String 返回描述修改键的String,如Shift或Ctrl+Shift
getKeyText(int keyCode) String 返回描述keyCode的String,如HOME、F1或A
isActionKey() boolean 返回此事件中的键是否为“动作”键
setKeyChar(char keyChar)   设置keyCode值,以表示某个逻辑字符
setKeyCode(int keyCode)   设置keyCode值,以表示某个物理键

除了按键事件常用的方法之外,KeyEvent类还定义了按键常量,这些常量分别对应着按键的键值。常量名称以“VK_”为前缀。如VK_A常量代表按键A,它的键值是65。

Integer类的parseInt()方法将整数字符串转换成int基本类型的整数。该方法要求被转换的字符串对象只包含整数,否则会抛出NumberFormatException类的异常对象,说明数字格式异常。

Date类用于表示日期时间,它位于java.util包中。Date类最简单的构造方法就是默认的无参数的Date()构造方法,它使用系统中当前日期和时间创建并初始化Date类的实例对象。Date类的另一个构造方法是Date(long date),这个构造方法接收一个long类型的整数并初始化Date对象,这个long类型的整数是标准基准时间(称为“历元(epoch)”,即1970年1月1日00:00:00)开始的毫秒数。System类的currentTimeMillis()方法可以获取系统当前时间距历元的毫秒数。

after方法用于测试此日期是否在指定日期之后,返回true或false。befor方法与之相反。compareTo方法用于比较两个日期对象的顺序,常用语多个Date对象的排序,若相等,则返回0,否则返回一个大于0的值或小于0的值。

getTime方法返回自1970年1月1日00:00:00GMT以来此Date对象表示的毫秒数;setTime方法用于设置此Date对象,以表示1970年1月1日00:00:00GMT以后time毫秒的时间点。String类的静态format()方法通过特殊转义符作为参数可以实现对日期和时间的格式化。format()方法用于创建格式化的字符串,有两种重载形式:format(String format,Object ... args),该方法使用指定的格式字符串和参数返回一个格式化字符串。格式化后的新字符串使用本地默认的语言环境;format(Local local,String format,Object...args)。对于日期的格式化,可以使用转义符,把Date类的实例对象格式化。使用format()方法不但可以完成日期的格式化,也可实现时间的格式化。

常见的日期和时间组合的格式
转换符 说明 示例
%tF "年-月-日"格式(4位年份) 2008-03-25
%tD "月/日/年"格式(2位年份) 03/25/08
%tc 全部日期和时间信息 星期二 三月 25 15:20:00 CST 2008
%tT "时:分:秒 PM(AM)"格式(12时制) 03:22:06下午
%tT "时:分:秒"格式(24时制) 15:23:50
%tR “时:分”格式(24时制) 15:25

在Java语言中提供了一个执行数学基本运算的Math类,这个类包括一些常见的数学运算方法、这些方法包括三角函数方法、指数函数方法、对数函数方法、平方根函数方法等常用数学函数,除此之外该类还提供了一些常用的数学常量,如PI、E等。Math类包含的所有用于数学运算的函数方法,这些方法都是静态的,所以每个方法只要使用“Math.数学方法”就可以调用了。Math类还提供了角度和弧度相互转换的方法,如toRadians()、toDegrees()方法,但值得注意的是,角度和弧度的互换通常是不精确的。

在具体问题中取整操作使用的很普遍,Java中Math类的关键取整方法如下:

Math类中关键的取整方法说明
方法 说明 返回值类型
ceil(double a) 返回大于等于参数的最小整数 double
floor(double a) 返回小于等于参数的最大整数 double
rint(double a) 返回与参数最接近的整数,如果两个同为整数且数值接近,则结果取偶数 double
round(float a) 将参数加上1/2后返回与参数最近的整数 int
round(double a) 将参数加上1/2后返回与参数最近的整数,然后强制转换为长整型 long

Java中主要提供了两种方式产生随机数,分别为调用Math类的random方法和Random类提供的产生各种数据类型随机数的方法。在Math类中存在一个random()方法,用于产生随机数字,这个方法默认产生大于等于0.0,小于1.0的double型随机数,即0≤Math.random()<1.0。m+(int)(Math.Random()*n)返回一个大于等于m小于m+n(不包括m+n)之间的随机数。

使用Math类的random()方法也可以随机生成字符,如生成字符a~z之间的字符:(char)('a'+Math.random()*('z'-'a'+1));求任意两个字符之间的随机字符,可以使用:(char)(char1+Math.random()*(char2-char1+1));

Java还提供了一种可以获取随机数的方式,那就是java.util.Random类,通过实例化一个Random对象创建一个随机数生成器。以这种形式实例化对象时,Java编译器以系统当前时间作为随机数生成器的种子,另外也可以在实例化Random类对象时,设置随机数生成器的种子。

Java主要对浮点型数据进行数字格式化操作,其中浮点型数据包括double型和float型数据。在java中使用java.text.DecimalFormat类格式化数字,在Java中对没有格式化的数据遵循以下原则:如果数据绝对值大于0.01并小于10000000,java将以常规小数形式表示;如果数据绝对值小于0.01或大于10000000,使用科学计数法表示。

DecimalFormat是NumberFormat的一个子类,用于格式化十进制数字,它可以将一些数字格式化为整数、浮点数、科学计数法、百分数等。通过使用该类可以为要输出的数字加上单位或控制数字的精度。一般情况下可以在实例化DecimalFormat对象时传递数字格式,也可以通过DecimalFormat类中的applyPattern()方法来实现数字格式化。当格式化数字时,在DecimalFormat类中使用一些特殊字符构成一个格式化模板,使数字按照一定特殊字符规则进行匹配。

以“0”特殊字符构成的模板进行格式化,当某位数字不存在是,将补位显示0;以“#”特殊字符构成的模板进行格式化,格式化后的数字位数与数字本身的位数一致。还可以使用一些特殊方法对数字进行格式化设置:setGroupingSize()方法用于设置格式化数字的分组大小,而setGroupingUsed()方法用于设置是否可以对数字进行分组操作。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325646188&siteId=291194637