JAVA interview questions, java questions

Source: Internet
Author: User

JAVA interview questions, java questions

Here I will include some interesting interview questions I encountered during the interview.

The first interview question: ABC question, there are three threads, the work content is printed out "A", "B", "C ", what needs to be done is to output ABC in sequence, for example, ABCABCABCABC.

Idea 1: I think this function needs to be encapsulated and can be achieved. No matter how many threads can be printed in sequence, and basically no code needs to be changed. My idea is to encapsulate a Node as the first unit of work. The main task is to print and compete the lock and record the indexes added to the work, and then there is a ConcurrentHashMap storage working state. If all the work is finished, the last unit will refresh the status. The following is the implementation code:

Package com. hotusm. concurrent. test; import java. util. map; import java. util. treeMap; import java. util. concurrent. timeUnit; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock;/*** Created by luqibao on 2016/12/30. */public class ABCSample {private static ReentrantLock lock = new ReentrantLock (); private static volatile TreeMap <Integer, Node> indexs = new TreeMap <> (); publ Ic static void main (String [] args) {ReentrantLock lock = new ReentrantLock (); TreeMap <Integer, Node> indexs = new TreeMap <> (); node node1 = new Node ("A", lock, indexs, 0); Node node2 = new Node ("B", lock, indexs, 1 ); node node3 = new Node ("C", lock, indexs, 2); indexs. put (0, node1); indexs. put (1, node2); indexs. put (2, node3); node1.beforeWork (); node2.beforeWork (); node3.beforeWork (); try {TimeUnit. SECONDS. sleep (3);} c Atch (Exception e) {e. printStackTrace ();} node1.start (); node2.start (); node3.start (); synchronized (ABCSample. class) {try {ABCSample. class. wait ();} catch (Exception e) {e. printStackTrace () ;}} private static class WorkQueue {private Node tail; private Node head;} private static class Node extends Thread {private static volatile boolean isRefresh = false; private volatile Map <Integer, Node> maps; Private volatile boolean isWorked = false; private final int index; // index private String message; private volatile Lock readLock; private boolean isLast = false; public Node (String message, Lock lock, map <Integer, Node> maps, int index) {this. message = message; this. readLock = lock; this. maps = maps; this. index = index;} public int getIndex () {return index;} public void beforeWork () {readLock. lock (); try {if (Index = maps. size ()-1) {isLast = true;} else {isLast = false;} finally {readLock. unlock () ;}@ Override public void run () {while (true) {readLock. lock (); if (isRefresh) {continue;} try {if (this. index = 0 &&! This. isWorked) {System. out. print (this. message); this. isWorked = true;} else if (index! = 0) {Node node = maps. get (index-1); if (! Node. isWorked) {System. out. print (node. message); node. isWorked = true;} else {if (! This. isWorked) {System. out. print (this. message); this. isWorked = true;} else if (this. isWorked & this. isLast) {refresh () ;}}} catch (Exception e) {Thread. currentThread (). interrupt (); e. printStackTrace ();} finally {readLock. unlock ();} try {TimeUnit. SECONDS. sleep (1);} catch (Exception e) {e. printStackTrace () ;}} private void refresh () {isRefresh = true; for (Map. entry <Integer, Node> map: maps. entrySet () {map. getValue (). isWorked = false;} isRefresh = false ;}}}

In fact, there are still a lot of encapsulation areas above. registration can be encapsulated into a method, and the front-end work is also done. It can be marked with a volatile modified boolean. The same is true for startup. If yes, it is best to do this by calling a register (msg) and start ().

Train of Thought 2: because this is a ring link structure, we can notify you to keep the lock from the head and let others get it again. The following code:

Package com. hotusm. concurrent. test; import sun. misc. unsafe; import java. lang. reflect. field; import java. util. concurrent. countDownLatch;/*** Created by luqibao on. */public class ABCSample2 {public static void main (String [] args) {WorkQueue queue = new WorkQueue (); queue. addWork ("A"); queue. addWork ("B"); queue. addWork ("C"); queue. addWork ("D"); queue. addWork ("E"); queue. startWork (); synchroniz Ed (ABCSample2.class) {try {ABCSample2.class. wait ();} catch (Exception e) {e. printStackTrace () ;}} private static class WorkQueue {private Node head; private Node tail; private int num = 0; private static final Unsafe unsafe = getUnsafe (); private static final long tailOffset; private static final long headOffset; static {try {// obtain the memory location of the current field and use headOffset = unsafe. objectFieldOffset (Wo RkQueue. class. getDeclaredField ("head"); tailOffset = unsafe. objectFieldOffset (WorkQueue. class. getDeclaredField ("tail");} catch (Exception ex) {throw new Error (ex);} private static Unsafe getUnsafe () {try {Field singleoneInstanceField = Unsafe. class. getDeclaredField ("theUnsafe"); singleoneInstanceField. setAccessible (true); return (Unsafe) singleoneInstanceField. get (null);} catch (Ti On e) {throw new RuntimeException (e) ;}} protected void push (Node node) {for (;) {Node t = tail; if (t = null) {if (compareAndSetHead (node) num ++; tail = head; break;} else {if (compareAndSetTail (t, node) {num ++; t. next = node; break ;}}}/*** the order of adding work is the order of printing * @ param message printed information */public void addWork (String message) {Node node = new Node (message); push (node) ;}/ *** start working */publ Ic void startWork () {Node. head = this. head; Node. tail = tail; Node. latch = new CountDownLatch (num); Node. currentWork = head; for (Node node = head; node! = Null; node = node. next) {node. start (); Node. latch. countDown () ;}} public boolean compareAndSetTail (Node average CT, Node newValue) {return unsafe. compareAndSwapObject (this, tailOffset, exact CT, newValue);} public boolean compareAndSetHead (Node specific CT) {return unsafe. compareAndSwapObject (this, headOffset, null, exact CT) ;}} private static class Node extends Thread {private static volatile Node currentWork; priv Ate static volatile Node head; private static volatile Node tail; private static volatile CountDownLatch latch; private String message; private Node next; public Node (String message) {this. message = message ;}@ Override public void run () {try {latch. await ();} catch (Exception e) {e. printStackTrace () ;}for (;) {if (currentWork = this) {if (! "". Equals (message) {System. out. print (message) ;}if (this = tail) {currentWork = head;} else {currentWork = this. next ;}}}}}}

In general, I still like the latter, but still need optimization. For example, after the startup, I cannot add work, and the verification work cannot be repeated.

The second interview question:

The specific questions are as follows:-Java Development-functional requirements: o web crawler, you can use a small number of third-party libraries, but it is best to use your own code o + points: use multithreading, note that the synchronization and lock o will capture the "Internet, programming, and algorithm" books in book( book.douban.com, in addition, the top 100 pieces of data with the highest score (requires more than 2000 people to be evaluated, and the top 2000 will be extracted if less than 100) o Code and the crawled results (excel files) are stored in github, send the link to you and then send it to me.

This interview question is a topic of a top 500 foreign company. It is interesting because I have never been familiar with crawlers. The code is on our github: https://github.com/housum/crawl.git.

Because the time was relatively tight (during the day in the project), I wanted to write the network and parse it myself, but I didn't have time. So I used third-party products, but I felt that I had to remove the lock, others are third-party frameworks. The interviewer's comment is okay.

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.