Java multithreading interview questions Induction

Source: Internet
Author: User

Java multithreading interview questions Induction
1. What are the implementation methods for multithreading? The following example shows the thread synchronization.

(1) Java multithreading has two implementation methods: Inheriting the Thread class and implementing the Runnable interface. Thread implements the Runnable interface.

Two simple thread examples:

Package chc. runnable; public class ThreadTest2 {public static void main (String [] args) throws InterruptedException {Thread1 t = new Thread1 (); // t. run (); // The method t cannot be called directly here. start (); for (int I = 0; I <100; I ++) {System. out. println ("main:" + I) ;}} class Thread1 extends Thread {public void run () {for (int I = 0; I <100; I ++) {System. out. println ("Thread -----:" + I );}}}
Package chc. runnable; public class ThreadTest1 {public static void main (String [] args) {Runnable1 r = new Runnable1 (); Thread t1 = new Thread (r); t1.start ();}} class Runnable1 implements Runnable {public void run () {// TODO Auto-generated method stubfor (int I = 1; I <= 5; I ++) {System. out. println ("the thread implementing the Runnable interface ----->" + I );}}}

The preceding two examples show that starting a thread does not affect the execution of the main program.

(2) thread synchronization problems

Use the synchronnized keyword

Bank account money access problems:

Public class ThreadTest {public static void main (String [] args) {ThreadA t1 = new ThreadA (); t1.start (); ThreadB t2 = new ThreadB (); t2.start () ;}} class ThreadA extends Thread {@ Overridepublic void run () {for (int I = 0; I <100; I ++) {account. add (); try {sleep (10); // simulate the processing time of the banking system} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}} class ThreadB extends Thread {@ Overridepublic void run () {for (int I = 0; I <100; I ++) {account. remove (); try {sleep (10); // simulate the processing time of the banking system} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}} class account {public static int count = 1000; // subtract 100 yuan public static synchronized void remove () {count = count-100; System. out. println ("less than 100 yuan, card balance" + count);} // add 100 yuan public static synchronized void add () {count = count + 100; System. out. println ("plus 100 yuan, card balance" + count );}}
Note: In the above example, the add () and remove () Methods of the account class are added with the static keyword, because in this way, the two methods can be called directly through the class name in the thread, you do not need to instantiate an object.

Because synchronized synchronization is only valid for methods in the same object, that is, one thread is executing the add () method of the account, and the other thread can call the add method of another object.

2. What is the difference between running () and start () when starting a thread?

Of course it is start (). When the start () method of the thread is called, the thread enters the ready state.

The run () method is the thread's execution entry. When a thread enters the execution state from the ready state, it must start to run from the run () method.

Of course, we can also directly call the run () method of this object through the thread object, but this is only a common call and does not start any thread.

When we call the start () method, another thread is started to execute the code of the thread class, which does not affect the execution of the main program, but calls run () wait for the code execution in the run () method

The main program can be executed downward. For example:

Public class ThreadDemo2 {public static void main (String [] args) {Thread5 t1 = new Thread5 (); Thread6 t2 = new Thread6 (); t1.run (); t2.start (); for (int I = 0; I <100; I ++) {System. out. println ("main process execution:" + I) ;}} class Thread5 extends Thread {@ Overridepublic void run () {for (int I = 0; I <100; I ++) {System. out. println ("Thread5 execution:" + I) ;}} class Thread6 extends Thread {@ Overridepublic void run () {for (int I = 0; I <100; I ++) {System. out. println ("Thread6 execution:" + I );}}}
The output sequence is: after all Thread5 is printed, Thread6 and the main program are printed alternately. Verified the above statement

3. When a thread enters the synchronized Method of an object, can other threads access other methods of this object?

Not necessarily, depending on the situation

If the static keyword is added to other methods, the method is a class, not an object, and cannot be synchronized with the method of the object (even if the synchronized keyword exists.

If other methods do not contain the static keyword and the synchronized keyword, they cannot be entered. If they do not, they can.

The second step is to check whether the wait () method has released the lock.

4. The sub-thread loops twice, the main thread loops three times, the sub-thread loops three times, and the main thread loops three times. In this way, write the program code.

Public class ThreadDemo5 {static boolean thread_flag = false; // indicates whether the Sub-thread loop ends static boolean main_flag = true; // call the start method of the sub-thread to true, when the thread_flag is set to true (that is, when the subthread completes the loop), the main thread completes the loop and changes to false; public static void main (String [] args) {for (int k = 0; k <5; k ++) {Thread7 t = new Thread7 (); t. start (); main_flag = true; while (main_flag) {// loop wait thread_fif (thread_flag) {for (int I = 0; I <3; I ++) {System. out. println ("first cycle of the main thread" + (I + 1) + "");} thread_flag = false; main_flag = false ;}}}}} class Thread7 extends Thread {static boolean flag = true; // indicates the nth loop of A subthread. When the value is true, the subthread loops twice, otherwise, the public void run () {if (flag) {for (int I = 0; I <2; I ++) {System. out. println ("subthread first loop" + (I + 1) + "times");} flag = false;} else {for (int I = 0; I <3; I ++) {System. out. println ("second loop of sub-thread" + (I + 1) + "");} flag = true;} ThreadDemo5.thread _ flag = true ;}}

This is to note that when calling the start method of the sub-thread, the main program cannot continue to be executed downward, so we need to mark it with variables.

5. What are the similarities and differences between sleep () and wait?

(1) first, the most obvious difference is that wait is an Object-class method, and sleep () is a static method of the Thread class. Who calls this method and who goes to sleep, even if the sleep method of thread B is called in thread a, the thread a goes to sleep.

(2) It is important that sleep does not release the lock, and wait releases the lock. Other threads can use synchronous block resources.

Sleep does not assign system resources; wait enters the thread wait pool to wait, and transfers system resources. Other threads can occupy the CPU. Generally, wait does not apply a time limit because it is useless if the Running Resources of the wait thread are insufficient.

Wait until other threads call y/notifyAll to wake up all threads in the wait pool before entering the ready queue to wait for the OS to allocate system resources. Sleep (milliseconds) can be automatically woken up by time.

Interrupt () can only be called to force interrupt.

(3) Scope of use:

Wait, policy, and policyall can only be used in synchronous control methods or synchronization control blocks, while sleep can be used anywhere.
Synchronized (x ){
X. Sort y ()
// Or wait ()
}

(4) sleep needs to capture exceptions, but wait does not.

6. Now there are three T1 T2 T3 threads. How can we ensure that T2. after T1 is executed, T3 is executed after T2 is executed?

This topic mainly describes the use of the join () method.

When thread B. join () is executed in thread A, thread A can be executed only after thread B is executed.

Public class JoinDemo {public static void main (String [] args) {T1 = new t1 ("T1"); T2 t2 = new T2 ("T2 "); t3 t3 = new T3 ("T3"); t1.start (); try {t1.join ();} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} t2.start (); try {t2.join ();} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}t3.start () ;}} class T1 extends Thread {private String name; public T1 (String name) {this. name = name ;}@ Overridepublic void run () {for (int I = 0; I <5; I ++) {try {sleep (5 );} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println (this. name + "loop" + I) ;}} class T2 extends Thread {private String name; public T2 (String name) {this. name = name ;}@ Overridepublic void run () {for (int I = 0; I <5; I ++) {try {sleep (5 );} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println (this. name + "loop" + I) ;}} class T3 extends Thread {private String name; public T3 (String name) {this. name = name ;}@ Overridepublic void run () {for (int I = 0; I <5; I ++) {System. out. println (this. name + "loop" + I );}}}

7. What are the similarities and differences between synchronized and java. util. concurrent. locks. Lock?

The main point is that Lock can complete all functions implemented by synchronized.

Major difference: Lock has more precise thread semantics and better performance than synchronized. Synchronized Automatically releases the Lock, which must be manually released by the programmer and must be released in the finally clause.

Lock also has more powerful functions. For example, its tryLock method can get the Lock in non-blocking mode.

8. deadlock

Supplement ......

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.