Summary of more database puzzles

Source: Internet
Author: User

1. When using multithreading, pay attention to the difference between the run method and the start method.
T. run (); the main thread calls the run method of t and does not create a new thread.

T. start (); Create a New thread t and execute it.

View plaincopy to clipboardprint? Public class PuzzleDemo76 {
Public static synchronized void main (String args []) {// The Master thread obtains the lock of the PuzzleDemo76 object.
Thread t = new Thread (){
Public void run (){
Pong ();
}
};
T. start ();
System. out. println ("ping ");
}
Static synchronized void pong () {// wait until the execution of the main thread is completed before the t thread can obtain the lock
System. out. println ("pong ");
}
}
Public class PuzzleDemo76 {
Public static synchronized void main (String args []) {// The Master thread obtains the lock of the PuzzleDemo76 object.
Thread t = new Thread (){
Public void run (){
Pong ();
}
};
T. start ();
System. out. println ("ping ");
}
Static synchronized void pong () {// wait until the execution of the main thread is completed before the t thread can obtain the lock
System. out. println ("pong ");
}
}

 

2. Notes for the join () method of Thread
Indicates that the linked Thread instance calls the wait method, so the lock is released.

Therefore, if you need full control of the lock of an object, you must ensure that no other thread is accessed.

View plaincopy to clipboardprint? Import java. util .*;
Public class PuzzleDemo77 {
Public static void main (String args []) throws Exception {
Final Worker w = new Worker ();
Thread t = new Thread (w );
T. start ();
Timer timer = new Timer (true );
Timer. schedule (new TimerTask (){
Public void run (){
W. keepWorking ();
}
},500 );
Thread. sleep (400 );
W. quit (); // obtain the w lock and execute the Method
}
}
Class Worker implements Runnable {
Private volatile boolean quitTime = false;
Public void run (){
While (! QuitTime ){
PretendToWork ();
}
System. out. println ("Beer is good ");
}
Private void pretendToWork (){
Try {
Thread. sleep (300 );
}
Catch (Exception e ){

}
}
Synchronized void quit () throws Exception {
QuitTime = true;
Thread. yield (); // release the lock
}
Synchronized void keepWorking (){
QuitTime = true;
}
}
Import java. util .*;
Public class PuzzleDemo77 {
Public static void main (String args []) throws Exception {
Final Worker w = new Worker ();
Thread t = new Thread (w );
T. start ();
Timer timer = new Timer (true );
Timer. schedule (new TimerTask (){
Public void run (){
W. keepWorking ();
}
},500 );
Thread. sleep (400 );
W. quit (); // obtain the w lock and execute the Method
}
}
Class Worker implements Runnable {
Private volatile boolean quitTime = false;
Public void run (){
While (! QuitTime ){
PretendToWork ();
}
System. out. println ("Beer is good ");
}
Private void pretendToWork (){
Try {
Thread. sleep (300 );
}
Catch (Exception e ){

}
}
Synchronized void quit () throws Exception {
QuitTime = true;
Thread. yield (); // release the lock
}
Synchronized void keepWorking (){
QuitTime = true;
}
}

 

3. HashSet Problems
HashSet <String> s = new HashSet <String> ();

Iterator I = s. iterator (); here I is of the HashMap. keyIterator type. However, because this type is not public in different packages, its method cannot be called.

Class HashSet {

Private transient HashMap <E, Object> map;

Public Iterator <E> iterator (){
Return map. keySet (). iterator ();
}

}
 

View plaincopy to clipboardprint? Import java. util .*;
Import java. lang. reflect .*;
Public class PuzzleDemo78 {
Public static void main (String args []) throws Exception {
Set <String> s = new HashSet <String> ();
S. add ("foo ");
Iterator iter = s. iterator ();
Method m = Iterator. class. getMethod ("hasNext ");
System. out. println (m. invoke (iter ));
}
}
Import java. util .*;
Import java. lang. reflect .*;
Public class PuzzleDemo78 {
Public static void main (String args []) throws Exception {
Set <String> s = new HashSet <String> ();
S. add ("foo ");
Iterator iter = s. iterator ();
Method m = Iterator. class. getMethod ("hasNext ");
System. out. println (m. invoke (iter ));
}
}


4. the compiler looks for a method calling rule: Find the method to be called in the inmost scope of the correct name method.


5. Class. newInstance and internal Class
Class. newInstance () is an empty constructor.

When a non-static internal class calls an empty constructor, there will be a hidden parameter, that is, an external class instance. Therefore, the external looks like an empty internal class constructor is not an empty constructor.

Conclusion: Avoid using reflection to instantiate internal classes.

View plaincopy to clipboardprint? Import java. lang. reflect .*;
Public class PuzzleDemo80 {
Public static void main (String args []) throws Exception {
New PuzzleDemo80 (). greetWorld ();
}
Private void greetWorld () throws Exception {
Constructor c = Inner. class. getConstructor (PuzzleDemo80.class );
System. out. println (c. newInstance (PuzzleDemo80.this ));
}
Public class Inner {
Public Inner (){}
Public String toString (){
Return "Hellow ";
}
}
}
Import java. lang. reflect .*;
Public class PuzzleDemo80 {
Public static void main (String args []) throws Exception {
New PuzzleDemo80 (). greetWorld ();
}
Private void greetWorld () throws Exception {
Constructor c = Inner. class. getConstructor (PuzzleDemo80.class );
System. out. println (c. newInstance (PuzzleDemo80.this ));
}
Public class Inner {
Public Inner (){}
Public String toString (){
Return "Hellow ";
}
}
}

 

6. A flaw in System. out
System. out is a PrintStream with a buffer, but can be automatically refreshed.

But there is a method exception!

Write (int) is the only method that does not refresh the output stream of PrintStream when the automatic refresh function is enabled.

View plaincopy to clipboardprint? Public class PuzzleDemo81 {
Public static void main (String args []) {
String greeting = "Hello ";
For (int I = 0; I <greeting. length (); I ++ ){
System. out. println (greeting. charAt (I ));
}
}
}
Public class PuzzleDemo81 {
Public static void main (String args []) {
String greeting = "Hello ";
For (int I = 0; I <greeting. length (); I ++ ){
System. out. println (greeting. charAt (I ));
}
}
}

 

7. Simple methods and solutions for copying objects
Classes that implement io. serializable can simply copy objects through writeObject and readObject and generate a new object.

If a class is Singleton and therefore can only have one object, how can we solve this problem so that the objects after writeObject and readObject are themselves?

Private Object readResolve (){

Return **;

}

View plaincopy to clipboardprint? Import java. io .*;
Class Dog extends Exception {
Public static final Dog INSTANCE = new Dog ();
Private Dog (){}
Public String toString (){
Return "woof ";
}
Private Object readResolve () {// implements the readResolve method, so that there is only one instance
Return INSTANCE;
}
}
Public class PuzzleDemo83 {
Public static void main (String args []) throws Exception {
Dog dog = Dog. INSTANCE;
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("1.txt "));
Out. writeObject (dog );
Out. close ();
ObjectInputStream in = new ObjectInputStream (new FileInputStream ("1.txt "));
Dog dog2 = (Dog) in. readObject ();
In. close ();
System. out. println (dog = dog2 );
}
}
Import java. io .*;
Class Dog extends Exception {
Public static final Dog INSTANCE = new Dog ();
Private Dog (){}
Public String toString (){
Return "woof ";
}
Private Object readResolve () {// implements the readResolve method, so that there is only one instance
Return INSTANCE;
}
}
Public class PuzzleDemo83 {
Public static void main (String args []) throws Exception {
Dog dog = Dog. INSTANCE;
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("1.txt "));
Out. writeObject (dog );
Out. close ();
ObjectInputStream in = new ObjectInputStream (new FileInputStream ("1.txt "));
Dog dog2 = (Dog) in. readObject ();
In. close ();
System. out. println (dog = dog2 );
}
}


8. Differences between Thread. interrupted () and Thread. isInterrupted ()
The Thread. interrupted () method clears the interrupt status of the current Thread.

Thread. isInterrupted () is only used to test whether the Thread has been interrupted.

View plaincopy to clipboardprint? Public class PuzzleDemo84 {
Public static void main (String args []) {
Thread. currentThread (). interrupt ();
If (Thread. currentThread (). isInterrupted
 
()){
System. out. println
 
("Interrupt:" + Thread. currentThread (). isInterrupted ());
}
Else {
System. out. println ("Not
 
Interrupt: "+ Thread. currentThread (). isInterrupted ());
}
}
}
Public class PuzzleDemo84 {
Public static void main (String args []) {
Thread. currentThread (). interrupt ();
If (Thread. currentThread (). isInterrupted

()){
System. out. println

("Interrupt:" + Thread. currentThread (). isInterrupted ());
}
Else {
System. out. println ("Not

Interrupt: "+ Thread. currentThread (). isInterrupted ());
}
}
}


9. multi-thread Initialization
Before a thread accesses a member of a class, it checks whether the class has been initialized.

Class initialization in multiple threads can be performed in four cases:

(1) This class is not initialized.

(2) This class is initialized by the current thread.

(3) This class is initialized by other threads.

(4) This class has been initialized.

In the third case, if A line B wants to access A member of Class A, it finds that it is being initialized by the C thread, and it will wait until the C thread Initialization is complete before it continues to run.

Conclusion: The initialization sequence should be clarified.

View plaincopy to clipboardprint? Public class PuzzleDemo85 {
Private static boolean initialize = true; // 1
Private static Thread t = new Thread (new Runnable () {// 2
Public void run (){
Initialize = true;
}
});
Static {
System. out. println (initialize );
T. start (); // 3

}
Public static void main (String args []) {
Try {
System. out. println ("main:" + initialize );
T. join (); // 4
}
Catch (Exception e ){}
System. out. println (initialize); // 5
}
}
Public class PuzzleDemo85 {
Private static boolean initialize = true; // 1
Private static Thread t = new Thread (new Runnable () {// 2
Public void run (){
Initialize = true;
}
});
Static {
System. out. println (initialize );
T. start (); // 3

}
Public static void main (String args []) {
Try {
System. out. println ("main:" + initialize );
T. join (); // 4
}
Catch (Exception e ){}
System. out. println (initialize); // 5
}
}

Author: "xiazdong's column"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.