Google multi-threaded interview questions: 4 threads Write data to 4 files, each thread can write only one value

Source: Internet
Author: User

by Long Luo

Personal blog Links

Recently in the study Java多线程 , encountered a following pen question, the topic is as follows:

编写一个程序,程序会启动4个线程,向4个文件A,B,C,D里写入数据,每个线程只能写一个值。     线程A:只写A    线程B:只写B     线程C:只写C     线程D:只写D 4个文件A,B,C,D。 程序运行起来,4个文件的写入结果如下:     A:ABCDABCD...     B:BCDABCDA...     C:CDABCDAB...     

Online search, as if still a Google pen questions , the problem involves the knowledge points are:,, 多线程 并发 , 线程间通信 .

Personal Analysis Process:
1. 创建4个线程;2. 每个线程在输出时都需要加锁;3. 操作文件的代码要加锁;4. 一个线程完成之后,通知下一个要执行的线程;

According to the above analysis, the following code can be written:

Package Com.imlongluo.practise;import Java.io.bufferedwriter;import Java.io.file;import java.io.FileOutputStream; Import Java.io.outputstreamwriter;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class Practise {public        static void Main (string[] args) {Final task task = new Task ();            /** Create 4 threads and start at the same time *//** * thread A */New Thread (new Runnable () {@Override                public void Run () {for (int i = 0; i <; i++) {Task.outputa ();        }}}, "Thread A"). Start ();                /** * Thread B */New Thread (new Runnable () {@Override public void run () {                for (int i = 0; i < i++) {TASK.OUTPUTB ();        }}}, "Thread B"). Start ();    /** * Thread C * *    New Thread (New Runnable () {@Override public void run () {for (int i = 0; i < 10;                i++) {TASK.OUTPUTC ();        }}}, "Thread C"). Start ();                /** * Thread D */New Thread (new Runnable () {@Override public void run () {                for (int i = 0; i < i++) {TASK.OUTPUTD ();    }}}, "Thread D"). Start ();  }/** Task class */public static class Task {/** creates a lock lock object */private lock lock = new        Reentrantlock ();        Private BufferedWriter BW1 = null;        Private BufferedWriter bw2 = null;        Private BufferedWriter bw3 = null;        Private BufferedWriter bw4 = null;        private int ctl = 0;        /** * Condition: Thread condition */private Condition cond1 = Lock.newcondition ();  Private Condition Cond2 = Lock.newcondition ();      Private Condition Cond3 = Lock.newcondition ();        Private Condition Cond4 = Lock.newcondition ();        Private boolean[] Outputthisround = {False, True, True, true}; Public Task () {try {bw1 = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (New F                Ile ("/users/luolong/code/android/workspace/multithreads/a.txt"))); BW2 = new BufferedWriter (new OutputStreamWriter (New FileOutputStream new File ("/users/luolong/code                /android/workspace/multithreads/b.txt "))); BW3 = new BufferedWriter (new OutputStreamWriter (New FileOutputStream new File ("/users/luolong/code                /android/workspace/multithreads/c.txt "))); BW4 = new BufferedWriter (new OutputStreamWriter (New FileOutputStream new File ("/users/luolong/code            /android/workspace/multithreads/d.txt "))); } catch (Exception e) {E.printStackTrace ();            }} public void Outputa () {lock.lock ();                    try {while (Outputthisround[0]) {System.out.println ("Outputa begin to Await!"); Cond1.await ();                    Block A thread} if (ctl% 4 = = 0) {bw1.write ("a");                Bw1.flush ();                    } else if (ctl% 4 = = 1) {bw4.write ("A");                Bw4.flush ();                    } else if (ctl% 4 = = 2) {bw3.write ("A");                Bw3.flush ();                    } else if (ctl% 4 = = 3) {bw2.write ("A");                Bw2.flush ();                } Outputthisround[0] = true;                OUTPUTTHISROUND[1] = false;                SYSTEM.OUT.PRINTLN ("Outputa signal outputb!"); Cond2.signal ();            Wake b Thread} catch (Exception e) {e.printstacktrace (); } finally {lock.unlock ();            }} public void Outputb () {lock.lock ();                    try {while (outputthisround[1]) {System.out.println ("OUTPUTB begin to Await!");                Cond2.await ();                    } if (ctl% 4 = = 0) {bw2.write ("B");                Bw2.flush ();                    } else if (ctl% 4 = = 1) {bw1.write ("B");                Bw1.flush ();                    } else if (ctl% 4 = = 2) {bw4.write ("B");                Bw4.flush ();                    } else if (ctl% 4 = = 3) {bw3.write ("B");                Bw3.flush ();                } outputthisround[1] = true;                OUTPUTTHISROUND[2] = false;                SYSTEM.OUT.PRINTLN ("OUTPUTB signal outputc!");            Cond3.signal ();            } catch (Exception e) {e.printstacktrace (); } finAlly {Lock.unlock ();            }} public void Outputc () {lock.lock ();                    try {while (outputthisround[2]) {System.out.println ("OUTPUTC begin to Await!");                Cond3.await ();                    } if (ctl% 4 = = 0) {bw3.write ("C");                Bw3.flush ();                    } else if (ctl% 4 = = 1) {bw2.write ("C");                Bw2.flush ();                    } else if (ctl% 4 = = 2) {bw1.write ("C");                Bw1.flush ();                    } else if (ctl% 4 = = 3) {bw4.write ("C");                Bw4.flush ();                } outputthisround[2] = true;                OUTPUTTHISROUND[3] = false;                SYSTEM.OUT.PRINTLN ("OUTPUTC signal outputd!");            Cond4.signal ();            } catch (Exception e) {e.printstacktrace (); }finally {Lock.unlock ();            }} public void Outputd () {lock.lock ();                    try {while (Outputthisround[3]) {System.out.println ("OUTPUTD begin to Await!");                Cond4.await ();                    } if (ctl% 4 = = 0) {bw4.write ("D");                Bw4.flush ();                    } else if (ctl% 4 = = 1) {bw3.write ("D");                Bw3.flush ();                    } else if (ctl% 4 = = 2) {bw2.write ("D");                Bw2.flush ();                    } else if (ctl% 4 = = 3) {bw1.write ("D");                Bw1.flush ();                } Outputthisround[3] = true;                Outputthisround[0] = false;                ctl++;                SYSTEM.OUT.PRINTLN ("OUTPUTD signal outputa!");            Cond1.signal (); } catch (Exception e) {e.printstAcktrace ();            } finally {Lock.unlock (); }        }    }}

Above.

If you have other better ways, welcome to discuss:-).

Created by Long Luo in 2015-04-09 22:14:02 @Shenzhen, China. completed by Long Luo in 2015-04-09 23:46:29 @Shenzhen, China.

Google multi-threaded interview questions: 4 threads Write data to 4 files, each thread can write only one value

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.