Tag Archives: java

Spring boot problem solving record (1)

exercise author: pure smile project spring-boot-examples encountered problems

problem 1:

demo spring – the boot – web: maven error after install Failed to execute goal. Org. Apache maven. Plugins: maven – surefire plugin: 2.22.1: test (default – test) on the project spring – the boot – web: There are test failures.

solution: add configuration skip test

at the bottom of the pot.xml


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!--添加配置跳过测试-->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.22.1</version>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>
			<!--添加配置跳过测试-->
		</plugins>
	</build>

question 2: we are Unable to import maven project: See logs for details by clicking the maven reimport icon

view error log: Help> > Show Log in finder (Help> > Show Log in Explorer)

2020-10-19 09:12:17,669 [ 538013]  ERROR -      #org.jetbrains.idea.maven - com.google.inject.CreationException: Unable to create injector, see the following errors:

1) No implementation for org.apache.maven.model.path.PathTranslator was bound.
  while locating org.apache.maven.model.path.PathTranslator
    for field at org.apache.maven.model.interpolation.AbstractStringBasedModelInterpolator.pathTranslator(Unknown Source)
  at org.codehaus.plexus.DefaultPlexusContainer$1.configure(DefaultPlexusContainer.java:350)

2) No implementation for org.apache.maven.model.path.UrlNormalizer was bound.
  while locating org.apache.maven.model.path.UrlNormalizer
    for field at org.apache.maven.model.interpolation.AbstractStringBasedModelInterpolator.urlNormalizer(Unknown Source)
  at org.codehaus.plexus.DefaultPlexusContainer$1.configure(DefaultPlexusContainer.java:350)

2 errors 
java.lang.RuntimeException: com.google.inject.CreationException: Unable to create injector, see the following errors:

1) No implementation for org.apache.maven.model.path.PathTranslator was bound.
  while locating org.apache.maven.model.path.PathTranslator
    for field at org.apache.maven.model.interpolation.AbstractStringBasedModelInterpolator.pathTranslator(Unknown Source)
  at org.codehaus.plexus.DefaultPlexusContainer$1.configure(DefaultPlexusContainer.java:350)

2) No implementation for org.apache.maven.model.path.UrlNormalizer was bound.
  while locating org.apache.maven.model.path.UrlNormalizer
    for field at org.apache.maven.model.interpolation.AbstractStringBasedModelInterpolator.urlNormalizer(Unknown Source)
  at org.codehaus.plexus.DefaultPlexusContainer$1.configure(DefaultPlexusContainer.java:350)

2 errors
	at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:543)
	at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:159)
	at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:106)
	at com.google.inject.Guice.createInjector(Guice.java:87)
	at com.google.inject.Guice.createInjector(Guice.java:69)
	at com.google.inject.Guice.createInjector(Guice.java:59)
	at org.codehaus.plexus.DefaultPlexusContainer.addComponent(DefaultPlexusContainer.java:344)
	at org.codehaus.plexus.DefaultPlexusContainer.addComponent(DefaultPlexusContainer.java:332)
	at org.jetbrains.idea.maven.server.Maven3ServerEmbedderImpl.customizeComponents(Maven3ServerEmbedderImpl.java:557)
	at org.jetbrains.idea.maven.server.Maven3ServerEmbedderImpl.customize(Maven3ServerEmbedderImpl.java:527)
	at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:564)
	at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
	at sun.rmi.transport.Transport$1.run(Transport.java:200)
	at sun.rmi.transport.Transport$1.run(Transport.java:197)
	at java.security.AccessController.doPrivileged(AccessController.java:691)
	at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
	at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:587)
	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:705)
	at java.security.AccessController.doPrivileged(AccessController.java:391)
	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:704)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
	at java.lang.Thread.run(Thread.java:832)
	at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:276)
	at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:253)
	at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:162)
	at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
	at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
	at com.sun.proxy.$Proxy165.customize(Unknown Source)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.execution.rmi.RemoteUtil.invokeRemote(RemoteUtil.java:179)
	at com.intellij.execution.rmi.RemoteUtil.access$300(RemoteUtil.java:39)
	at com.intellij.execution.rmi.RemoteUtil$2$1$1.compute(RemoteUtil.java:160)
	at com.intellij.openapi.util.ClassLoaderUtil.runWithClassLoader(ClassLoaderUtil.java:66)
	at com.intellij.execution.rmi.RemoteUtil.executeWithClassLoader(RemoteUtil.java:231)
	at com.intellij.execution.rmi.RemoteUtil$2$1.invoke(RemoteUtil.java:157)
	at com.sun.proxy.$Proxy165.customize(Unknown Source)
	at org.jetbrains.idea.maven.server.MavenEmbedderWrapper.doCustomize(MavenEmbedderWrapper.java:96)
	at org.jetbrains.idea.maven.server.MavenEmbedderWrapper.lambda$customizeForResolve$1(MavenEmbedderWrapper.java:69)
	at org.jetbrains.idea.maven.server.RemoteObjectWrapper.perform(RemoteObjectWrapper.java:76)
	at org.jetbrains.idea.maven.server.MavenEmbedderWrapper.customizeForResolve(MavenEmbedderWrapper.java:68)
	at org.jetbrains.idea.maven.project.MavenProjectsTree.resolve(MavenProjectsTree.java:1272)
	at org.jetbrains.idea.maven.project.MavenProjectsProcessorResolvingTask.perform(MavenProjectsProcessorResolvingTask.java:45)
	at org.jetbrains.idea.maven.project.MavenProjectsProcessor.doProcessPendingTasks(MavenProjectsProcessor.java:134)
	at org.jetbrains.idea.maven.project.MavenProjectsProcessor.access$000(MavenProjectsProcessor.java:32)
	at org.jetbrains.idea.maven.project.MavenProjectsProcessor$2.run(MavenProjectsProcessor.java:109)
	at org.jetbrains.idea.maven.utils.MavenUtil.lambda$runInBackground$5(MavenUtil.java:451)
	at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:314)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)
2020-10-19 09:12:17,670 [ 538014]  ERROR -      #org.jetbrains.idea.maven - IntelliJ IDEA 2018.3.5  Build #IU-183.5912.17 
2020-10-19 09:12:17,670 [ 538014]  ERROR -      #org.jetbrains.idea.maven - JDK: 1.8.0_152-release; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o 
2020-10-19 09:12:17,670 [ 538014]  ERROR -      #org.jetbrains.idea.maven - OS: Mac OS X 
2020-10-19 09:12:17,686 [ 538030]  ERROR -      #org.jetbrains.idea.maven - Last 

cause: Maven3.6.2 version compatibility issues.
solution: download the lower version of Maven3.6.0 and the following versions to solve the problem.

Elasticsearch6. X invalid time range query bug

elasticsearch6.x time-range query invalid bug

1.es6.8.1 time range query, the original writing is as follows:

GET /oms_historyalarm.historyalarm_recent/historyalarm_recent/_search
{
    "query":{
             "range":{
                "fault_start_time":{
                    "from":"2019-10-28 00:00:00",
                    "to":"2019-10-28 17:46:03",
                    "format": "yyyy-MM-dd hh:mm:ss"
                  }
              }
      }
}

query results are as follows:

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}
2. Looked up many baidu resources but could not find a solution, finally went back to check the field type of es index, found that fault_start_time field storage type is String, in this case, es will default to participle query again, of course, but no return.

solution: simply identify the time field that needs to be filtered as a keyword and then es will not participle it. As follows:

GET /oms_historyalarm.historyalarm_recent/historyalarm_recent/_search
{
    "query":{
             "range":{
                 "fault_start_time.keyword":{
                     "from":"2019-10-28 00:00:00",
                     "to":"2019-10-28 17:46:03",
                     "format": "yyyy-MM-dd hh:mm:ss"
                  }
              }
    }
}

result: of course successful

hope you can help, if you have any questions please leave a comment.

Idea has no code prompt solution when writing YML file

small white write springboot project, configuration yml file no code prompt, tried a lot of online methods, but did not find the answer, finally accidentally solved. I hope my method can help you.

I used idea2020, which should be updated. The yml file icon in 2020 has been changed, and there are no green leaves. The specific icon is like this.

if your icon looks like this, the software has recognized the yml file, but there is no code prompt, you need to download the yml plugin. Download plugins in setting.

Java query HBase outoforderscannernextexception

Java query hbase timeout, and sometimes an error OutOfOrderScannerNextException

there is only one message like this, no other error message

Caused by: org.apache.hadoop.hbase.exceptions.OutOfOrderScannerNextException: org.apache.hadoop.hbase.exceptions.OutOfOrderScannerNextException: Expected nextCallSeq: 1 But the nextCallSeq got from client: 0; request=scanner_id: 178 number_of_rows: 100 close_scanner: false next_call_seq: 0

then I trim the rowkey, make it the same length, and there it is…

Some problems and solutions of Java Web

Java web part problem and solution

The
error is based on the number of errors that occur in the writing process. Careful examination, rigorous scholarship!

JSP images cannot display properly?
found problem: path problem, path is incomplete.

shows a serious error, how many lines:
is generally in the select statement related character input error, carefully check.

request-getparameter (” ID “) where the parameter comes from
where the JSP page jumps over, the ID is the ID from the jump join of that page.

solve the import project, add Tomcat and JDK after the project appears Red Cross : modify the JDK version of the project and eclipse version of the JDK version. J compiler and project facts in
project (JAVA, WWM, and runtimes modified Tomcat version on the right).

Java web project, after starting Tomcat, display:
information.

describes a source server that was unable to find a representation of the target resource or was unwilling to expose an existing representation of the resource.
tries to find that since there was a related shop project originally, although the name was changed later, the new import project named shop was affected. When adding to Tomcat, the Path name was shop3 in web modules, and when accessing with the browser, it should be noted that the Path name was shop3 instead of shop.

2020.10.18
eclipse json file error, because eclipse thinks that json file does not need annotation, so compile error.
address: Prefrences, validation, json validator, cancel manual, build. Again, right click and validation on the json file that is in error.

valicat trial expires, modify system time before the probation period:
address: https://jingyan.baidu.com/article/adc815133376b6b622bf7354.html

Publishing to Tomcat v9.0 Server at localhost…
Publishing the configuration…
Error file to E:/download/apache-tomcat-9.0.38-windows-x64/apache-tomcat-9.0.38/backup\ sys_loginmapper.xml :
E:\ Download \ Apache-Tomcat-9.0.38-Windows-x64 \ Apache-Tomcat-9.0.38 \conf\ SYs_loginmapper.xml (the system cannot find the specified file)
E:\download\apache-tomcat-9.0.38-windows-x64\apache-tomcat-9.0.38\conf\ sys_loginmapper.xml (the system could not find the specified file)
OK

resolve in eclipse-> Project Explorer-> Servers-> Under Tomcat, sys_loginmapper. XML file was found and copied to:
Error file to E:/download/apache-tomcat-9.0.38-windows-x64/apache-tomcat-9.0.38/backup to solve the problem.

start Tomcat anomalies: Java. Lang. NoClassDefFoundError: javax.mail/XML/bind/is thrown.
j is the JDK version problem, I used jdk11, changed to jdk8 can be used normally, the reason for the error should be the introduction of JDK 9 and the version of Java modularity mechanism.

start Tomcat error:
Could not publish server configuration for Tomcat v9.0 server at localhost. Multiple Contexts have a path of “/ MRBBS”. Project Explorer-> Servers-> Server.xml file was found under Tomcat, and found at the bottom:
< The Context the docBase = “MRBBS” path = “/ MRBBS” reloadable = “true” source = “org. Eclipse. JST. Jee. Server: MRBBS”/& gt;
delete duplicate content, you can.

start Tomcat outbreak exception:
Could not get JDBC Connection;
Request processing failed; Nested exception is org. Mybatis. Spring. MyBatisSystemException: nested exception is
org. Apache. Ibatis. Exceptions. PersistenceException:
why : When the Spring container manages the PropertySource, not only does it read its own properties file, but it also reads both JVM system properties and
JVM system env properties into the container.
so at this point the username read in spring-transaction.xml is not the username above JDBC.
solution , change the username on jdbc.properties to user (as long as it is not called username), and change the values in the spring-transaction.xml corresponding to
to correspond:

When Tomcat is started, an exception occurs:
serverTimezone problem.
JDBC in the configuration file. The properties of add after url:
url = JDBC: mysql:// 127.0.0.1:3306/MRBBS
url = JDBC: mysql:// 127.0.0.1:3306/MRBBS?ServerTimezone =Asia/Shanghai
change to east area 8 time.

Global lock, table lock and row lock in MySQL

🔒 global lock

locks the entire database instance. Use the Flush tables with read lock (FTWRL) to keep the entire database read-only, after which the database update statement (add, delete), data definition statement (build, modify table structure), and update class transaction commit statement will be blocked

locks the entire database, so an obvious use case for global locks would be to do a full library logical backup; There is another way to use set global readonly=true to make the entire library read-only, with one big difference:

exception handling, if the client is abnormal to disconnect, MySQL will automatically release the global lock, so that the whole library back to the normal state; After the entire library is set to READOnly, the database will remain readOnly after the exception is disconnected, resulting in the database being unwritable for a long time.

🔒 table level lock

MySQL has two table level locks: table lock and meta data lock (MDL)

table lock syntax lock tables... Read /write, unlock unlock talbes. It is automatically released when the client is disconnected. In addition to restricting the reading and writing of other threads, table locks also restrict the following operation objects of this thread. For example, thread A executes lock tables t1 read,t2 write, while other threads write t1 and read t2 are blocked. Before tables, A thread can only read t1 and write t2

metadata lock is automatically added when accessing a table to ensure that the table structure cannot be modified

when accessing data

🔒 row locks

MySQL row lock is implemented in each storage engine, InnoDB on the support of row lock, MyISAM engine does not support row lock

row lock is the lock that locks A row of records in the table. When A is processing this row of data and B also wants to process this data, B can only continue

after A has finished processing

two-stage locking protocol

in InnoDB transactions, row locks are added when they are needed, but they are not immediately released when they are not needed, but wait until the current transaction is completed.

so if more than one row needs to be locked in a transaction, put the rows that are most likely to cause concurrency as far back as possible.

an 🌰 :

the ticketing business of a ticketing system is approximately:

  1. customer A ticket, A balance to deduct price

  2. cinema B account balance increase ticket

  3. record transaction log

    , the point of concurrency is cinema B to increase revenue. If each customer purchases tickets in the business order of 1, 2, and 3, then concurrent point 2 will hold the lock for a long time. If you change it to 3, 1, or 2 after processing the concurrent points, the row-level lock is released, reducing the wait time for locks between things.

    deadlock and deadlock detection

    different threads hold each other’s locks, A and B release the lock, B and A release the lock, then deadlock

    deadlock treatment strategy:

    1. one strategy is to go straight into the wait until the timeout occurs. This timeout can be set with the parameter innodb_lock_wait_timeout to

    2. to initiate deadlock detection. When a deadlock is found, it will actively roll back a transaction in the death chain bar to allow other transactions to continue execution. The parameter innodb_deadlock_detect is set to on, indicating that this logic is turned on,

      . Note here:

      (1) deadlock detection is performed only when there is a row lock on the accessed row

      (2) not all transactions are scanned for each deadlock detection. For example, at some point, the transaction waiting state is like this:

      , B is waiting for A, D is waiting for C, and now there is an E, and it is found that E needs to wait for D, then E will judge whether there will be deadlock with D and C, this detection does not care about B and A

Solve the problem that the value in the disabled tag cannot be passed to the server

disable tag values do not pass values to the server

<input type="text" name="did" value="${dept.did}" disabled="disabled"/><br/>

solution

  1. replace the field disabled in the form with readonly (if necessary, add a gray background color to the form)

    <input type="text" name="did" value="${dept.did}" readonly/><br/>
    

  2. you can write a hidden attributes, one for the value of a is used to display

    for example: add a hidden TAB and the name and value are set to the same value as the disable tag to successfully pass the value

    <input type="hidden" name="did" value="${dept.did}" >
    <input type="text" value="${dept.did}" disabled="disabled"/><br/>
    

    disabled

    similarity

    • can make text boxes cannot be entered.
    • can be modified by js script.
    • want to cancel, can only delete the corresponding attribute, set flase invalid

    different points

    disabled

    • input cannot receive focus
    • using the TAB key will skip the element
    • disabled will not respond to any event (e.g. the click event is invalid). The value of the disabled element
    • is not committed. The
    • disabled property can be used on all form elements.

    readonly

    • input can receive focus
    • use the TAB key does not skip elements
    • readonly will respond to events.
    • readonly element values are submitted. The
    • readonly property is only valid for type= “text”, textarea, and type= “password”.

    disabled will not be submitted to the server can’t be serialized but can be js can’t be modified on the interface all controls have disabled property

    readonly will be submitted to the server can be serialized can be js value assignment interface can’t modify all controls not necessarily have readonly property such as select drop down box

Multiple exceptions are caught in a single catch block

in Java7, the catch block has been upgraded to handle multiple exceptions in a single catch block.

code before Java7:

catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}catch (Exception ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

in Java7, we can catch all these exceptions with a catch

catch(IOException | SQLException | Exception ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

if multiple exceptions are handled with a catch block, they can be separated by a pipe, in which case the exception parameter variable ex is defined as final and cannot be modified. This feature will generate less bytecode and reduce code redundancy.

finally welcome to visit my personal website: 1024s

Java uses the same event listener for the same type of component

description

  • Java USES the same event listener for the same type of component to simplify the program and avoid writing duplicate code.
  • distinguishes different components by setting the name.

program code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextEve2 {

	public static void main(String[] args) {
		JFrame jf=new JFrame("test event");
		//创建多个同类型的事件源
		TextField tf1=new TextField(30);
		tf1.setName("tf1");
		TextField tf2=new TextField(30);
		tf2.setName("tf2");
		//注册事件监听器
		tf1.addTextListener(new MyTextListener());
		tf2.addTextListener(new MyTextListener());

		//添加组件
		Component strut = Box.createVerticalStrut(5);
		Box vBox = Box.createVerticalBox();
		vBox.add(tf1);
		vBox.add(strut);
		vBox.add(tf2);
		JPanel panel=new JPanel(new FlowLayout(FlowLayout.LEFT,5,10));
		panel.add(vBox);
		jf.add(panel);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.pack();
		jf.setVisible(true);
	}

	//自定义事件监听器
	private static class MyTextListener implements TextListener{
		@Override
		public void textValueChanged(TextEvent e) {
			TextField tf = (TextField) e.getSource();
			//根据不同事件源,执行不同的逻辑
			String name = tf.getName();
			switch (name){
				case "tf1":
					System.out.println("文本1内容= "+tf.getText());
					break;
				case "tf2":
					System.out.println("文本2内容= "+tf.getText());
					break;
				default:
					break;
			}
		}
	}
}


About Java File.separator

in Windows path separator and Linux path separator is different, when the absolute path is used directly, cross-platform will be exposed “No such file or diretory” exception.

File
File file1 = new File (“C:\ TMP \test.txt”);
File file1 = new File (“C:\ TMP \test.txt”)

File file2 = new File (“/ TMP /test.txt”);
File file2 = new File (“/ TMP /test.txt”);

if cross-platform is considered, it is best to say:
File myFile = new File(“C:” + file.separator + “TMP” + file.separator, “test.txt”);
File myFile = new File(“C:” + file.separator + “TMP” + file.separator, “test.txt”);

The

File class has several static fields that are similar to separator, which are system related and should be used as far as possible in programming.

separatorChar

public static final char separatorChar

is the default name separator associated with the system. This field is initialized to the first character that contains the system property file.separator value. On UNIX systems, the value of this field is ‘/’; On Microsoft Windows, it is ‘\’.

separator

public static final String separator

is the system-specific default name separator, which is represented as a string for convenience. This string contains only one character, separatorChar.

pathSeparatorChar

public static final char pathSeparatorChar

is the system-dependent path separator. This field is initialized as the first character that contains the system property path.separator value. This character is used to separate filenames in a given file sequence in the form of a path list. On UNIX systems, this field is ‘:’; On Microsoft Windows, it is ‘; ‘.

pathSeparator

public static final String pathSeparator

is the system-dependent path separator, which is represented as a string for convenience. This string contains only one character, pathSeparatorChar.

☞ warm prompt: to return to my blog index

The difference between sleep() and wait() in Java

learning just encounter these two methods, look up relevant information, and through the program to achieve, the difference:

Each object has a lock to control access to the synchronization, and the Synchronized keyword can interact with an object’s lock to implement Synchronized methods or blocks. sleep() sleep() lock lock! ). wait () method is refers to the current thread to temporarily retreat out the synchronous resource lock, so that other threads are waiting for the resource to get the resources, in turn, to run, only calls the notify () method, before calling wait () thread will lift its state of wait, can go to participate in the competition synchronous resource locks, and enforced. ( note: notify role is equivalent to wake the sleeping man, and would not give his assigned task, that is to say notify calling wait before just let the thread has the right to participate in the thread scheduling ).

2, sleep() can be used anywhere; wait() method can only be used in synchronized methods or synchronized blocks;

3, sleep() is the method of Thread. The call will suspend the specified time of this Thread, but the monitoring will still be maintained, and the object lock will not be released, and it will automatically recover at the time. wait() is an Object method. The call will give up the Object lock and enter the wait queue. The call notify()/notifyAll() will wake up the specified thread or all threads to enter the lock pool and run until the Object lock is acquired again.


to procedures:

public class MultiThread {

	private static class Thread1 implements Runnable{		
		@Override
		public void run() {
			//由于 Thread1和下面Thread2内部run方法要用同一对象作为监视器,如果用this则Thread1和Threa2的this不是同一对象
			//所以用MultiThread.class这个字节码对象,当前虚拟机里引用这个变量时指向的都是同一个对象
			synchronized(MultiThread.class){
				System.out.println("enter thread1 ...");
				System.out.println("thread1 is waiting");
				
				try{
					//释放锁有两种方式:(1)程序自然离开监视器的范围,即离开synchronized关键字管辖的代码范围
					//(2)在synchronized关键字管辖的代码内部调用监视器对象的wait()方法。这里使用wait方法
					MultiThread.class.wait();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				
				System.out.println("thread1 is going on ...");
				System.out.println("thread1 is being over!");
			}
		}
		
	}
	
	private static class Thread2 implements Runnable{
		@Override
		public void run() {	
			//notify方法并不释放锁,即使thread2调用了下面的sleep方法休息10ms,但thread1仍然不会执行
			//因为thread2没有释放锁,所以Thread1得不到锁而无法执行
			synchronized(MultiThread.class){
				System.out.println("enter thread2 ...");
				System.out.println("thread2 notify other thread can release wait status ...");
				MultiThread.class.notify();
				System.out.println("thread2 is sleeping ten millisecond ...");
				
				try{
					Thread.sleep(10);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				
				System.out.println("thread2 is going on ...");
				System.out.println("thread2 is being over!");
			}
		}		
	}
	
	public static void main(String[] args) {
		new Thread(new Thread1()).start();
		try{
			Thread.sleep(10);
		}catch(InterruptedException e){
			e.printStackTrace();
		}

		new Thread(new Thread2()).start();
	}

}

program results as shown in the figure below

Java – read all the files and folders in a certain directory and three methods to get the file name from the file path

1 reads all files and folders in a directory

public static ArrayList<String> getFiles(String path) {
    ArrayList<String> files = new ArrayList<String>();
    File file = new File(path);
    File[] tempList = file.listFiles();

    for (int i = 0; i < tempList.length; i++) {
        if (tempList[i].isFile()) {
//              System.out.println("文     件:" + tempList[i]);
            files.add(tempList[i].toString());
        }
        if (tempList[i].isDirectory()) {
//              System.out.println("文件夹:" + tempList[i]);
        }
    }
    return files;
}

2 3 ways to get the file name from the file path

package test;

import java.io.File;

public class FileName {

    /**
     * @param args
     */
    public static void main(String[] args) {
//      举例:
        String fName =" G:\\Java_Source\\navigation_tigra_menu\\demo1\\img\\lev1_arrow.gif ";

//      方法一:

        File tempFile =new File( fName.trim());

        String fileName = tempFile.getName();

        System.out.println("fileName = " + fileName);

//      方法二:

        String fName = fName.trim();

        String fileName = fName.substring(fName.lastIndexOf("/")+1);
        //或者
        String fileName = fName.substring(fName.lastIndexOf("\\")+1);

        System.out.println("fileName = " + fileName);

//      方法三:

        String fName = fName.trim();

        String temp[] = fName.split("\\\\"); /**split里面必须是正则表达式,"\\"的作用是对字符串转义*/

        String fileName = temp[temp.length-1];
        System.out.println("fileName = " + fileName);
    }
}