Frequently asked Questions for Java Multi-threading

Source: Internet
Author: User

Recently in the preparation of job interview questions, so found a lot of information, and self-organized related to the possible examination. Try to send an article every day.

1. Multithreading

Implementation method:

First, inherit the thread, rewrite the Run method, call start.

Class Thread1 extends thread{

public void Run () {

Add code

}

}

public static void Main (string[] args) {

Thread1st = new Thread1 ();

St.start ();

}

Second, implement the Runnable interface, rewrite the Run method, call start.

Class Runthrad implements runnable{

public void Run () {

Add code

}

}

Runthread t = new Runthread ();

Thread th = new Thread (t);

Th.start ();

Third, implement the Callable interface class, and override the call method, use the Futuretask class to wrap callable implements the object of the class, and use the Futuretask object as the target of the thread object to create the thread.

Class Mycallable implements callable<integer>{

public int call () {

Add code

}

}

public static void Main (string[] args) {

mycallable<integer> Mycall = new mycallable<integer> ();

futuretask<integer> ft = new futuretask<integer> (Mycall);

Thread th = new Thread (ft);

Th.start ();

}

The benefits of implementing runnable and callable than inheriting the thread method:

1, to avoid the problem of single inheritance.

2. Thread pool can only be put into runnable and callable classes.

There are five main types of threads, as follows:

Next, we introduce six methods of Sleep,wait,notify,notifyall,join,yield

For the Wait,notify,notifyall three, the method of the object class, but must be used with the synchronized synchronization block, that is, in the synchronized decorated synchronous code block or method calls wait or notify/ Notifyall:

Since Wait,notify/notifyall is placed in a synchronous code block, the thread must have entered a critical state when it was executed, that is, the thread must have acquired a lock.

When the wait method is executed, the current lock is freed, giving out the CPU and entering the waiting state.

When the Notify/notifyall method is executed, the thread that waits for the lock on the object is awakened, and then continues to execute until the synchronized code is executed and the lock is freed. (Note that Notify/notifyall does not immediately release the lock after execution, but waits to wait for the synchronized code to finish executing)

If thread A, thread B, threads A, execute wait, execute notify in threads B, and then thread B executes the notify and then ends, and then threads A does wait, thread A cannot be awakened at this point. For example: There are 3 threads a,b,c.

Class T implements runnable{

public String i;

Public String Index;

Public T (String i,string index) {

THIS.I = i;

This.index = index;

}

@Override

public void Run () {

Synchronized (index) {

while (true) {

try {

Index.notifyall ();

System.out.println (i);

Index.wait ();

} catch (Interruptedexception e) {

E.printstacktrace ();

}

}

}

}

}

public class Demo {

public static void Main (string[] args) {

String string1 = "S1";

String string2 = "S2";

String string3 = "S3";

String index = "Test";

T a1 = new T (string1,index);

T a2 = new T (string2,index);

T a3 = new T (string3,index);

Thread thread1 = new Thread (A1);

Thread thread2 = new Thread (A2);

Thread thread3 = new Thread (A3);

Thread1.start ();

Thread2.start ();

Thread3.start ();

}

}

Output Result:

S2

S1

S3

S1

S2

S1

S3

S1

......

Test the change of a condition in multi-threading with if or while?

I've never been able to understand when a condition needs to be tested in the run () method of a thread, why use while instead of if, until you see this simple example, finally understand ....

The example is this:

There are two threads that delete data from the list, and only one thread adds data to the list. Initially, the list is empty and the data in the list can be deleted only after the data has been added to the list. When the thread that added the data added data to the list, called Notifyall (), woke up two delete threads, but it only added one data and now has two wake-up delete threads, what do I do??

If you test the number of data in the list with the IF, you will get a indexoutofboundexception, out-of-bounds exception. The reason is that the list has only one data, the first delete thread after the data is deleted, the second thread to perform the delete operation, the deletion fails, thereby throwing indexoutofboundexception.

However, if you use while to test the number of data in the list, there will be no cross-border exceptions!!! Magic.

When the wait condition changes, the logic of the program is confusing---that there is no data in the list, and then the thread goes to perform the operation of deleting the data. Therefore, it is necessary to use the while loop to determine the condition change, rather than using the IF.

Two threads of communication can be used in the following two ways, one is based on while polling, the other is the way of wait/notify.

Based on while polling, the B thread has been looping the condition, throwing an exception and ending the thread when the condition is met.

A shared variable is used, based on the Wait/notify method. When a thread discards the CPU usage, enters the blocking state, the B thread gets the shared variable, starts execution, executes, the B thread ends, discards the CPU usage, and a thread continues. The easy problem is that a thread has not been executed, the B thread executes first, and the execution sequence is disrupted. The logical error.

Reference case in: http://www.cnblogs.com/hapjin/p/5492619.html

Sleep

Sleep lets the current thread hibernate for a specified time. When hibernation is complete, the state goes to ready state.

Yield:yield is to discard the current CPU resources and give the CPU resources to other threads to use, but the time to discard is uncertain.

Join

In most cases, the main thread initiates a child thread, and if the child thread needs to complete a large number of complex operations, the main thread will end up before the child thread. However, if you need to use the result of a child thread after the child thread has finished running, you must use join in the main thread so that the main thread waits for the child thread to end, and then the main thread ends.

Method join, which causes the owning thread object x to execute the Run method gracefully, causes the current thread Z to block indefinitely until the end of Object X, and then executes the code after Z.

public class Demo

{

public static void Main (string[] args) throws Interruptedexception

{

Thread producer = new producer ();

Producer.start ();

Producer.join ();

System.out.println ("main End");

}

}

Class Producer extends Thread

{

public void Run ()

{

for (int i = 0; i < 100000; i++)

System.out.println ("producer End");

}

}

In the above case, when Producer.join () is commented out, the main end is printed, and then the producer end is printed. Because the child threads are computationally complex, the main thread ends first. If you add this, the main thread will wait for the end of the producer, and then destroy the main path. That is, if a thread is called, it must wait for the thread to end and the primary thread of the call to proceed to the next step.

Frequently asked Questions for Java Multi-threading

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.