Java n threads take turns printing numbers problem

Source: Internet
Author: User


One. Implement two threads. Take turns to print out numbers. For example, the following:

Bthread---10aThread---9bThread---8aThread---- -3bThread-2aThread-1

Implemented with the lock class in Java:

Package Com.yjq.thread_demo;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class Twothreadprinter {private Lock Threadlock = new Reentrantlock (); Private Boolean flag = false;int count = 10; Thread athread = new Thread (new Runnable () {public void run () {while (true) {//Lock threadlock.lock (); try {if (Count < 1 ) {return;} if (flag) {//Athread task System.out.println ("Athread--" + (count--)); flag =!flag;}} catch (Exception e) {//Todo:handle Exception} finally {//release lock Threadlock.unlock ();}}}); Thread bthread = new Thread (new Runnable () {public void run () {while (true) {//Lock threadlock.lock (); try {if (Count < 1 ) {return;} if (!flag) {//Athread task System.out.println ("Bthread-to" + (count--)); flag =!flag;}} catch (Exception e) {//Todo:handle Exception} finally {//release lock Threadlock.unlock ();}}}); public void Starttwothread () {Athread.start (); Bthread.start ();} public static void Main (string[] args) {Twothreadprinter Twothreadprinter = nEW Twothreadprinter (); Twothreadprinter.starttwothread ();}} 


Implemented with synchronized:

Package Com.yjq.thread_demo;public class TwoThreadPrinter2 {Private Object threadlock = new object (); int count = 10; Thread athread = new Thread (new Runnable () {public void run () {while (true) {//Lock synchronized (Threadlock) {if (Count &l T 1) {return;} Athread task System.out.println ("Athread--" + (count--)); Threadlock.notify (); try {threadlock.wait ();} catch (Exception e) {//Todo:handle Exception}}}); Thread bthread = new Thread (new Runnable () {public void run () {while (true) {//Lock synchronized (Threadlock) {if (Count &l T 1) {return;} Athread task System.out.println ("Bthread--" + (count--)); Threadlock.notify (); try {threadlock.wait ();} catch (Exception e) {//Todo:handle Exception}}}});p ublic void Starttwothread () {Athread.start (); Bthread.start ();} public static void Main (string[] args) {Twothreadprinter twothreadprinter = new Twothreadprinter (); Twothreadprinter.starttwothread ();}}


Using the Lock class method is easier to understand. The block between lock () and Unlock () is locked


The Synchronize method uses less flag to flag which thread to print, because the thread lock's notifity () method releases the lock and wakes other threads, and the Wait () method of the thread lock releases the lock and sleeps the current thread, assuming that there are just two threads, Then it is natural to start with a thread and hibernate this thread.


Two. Scaling to n threads the problem of printing numbers in turn


n Threads print numbers in turn. Using the lock class is easier to extend


For example, three threads take turns to print a number

Package Com.myexample.test;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.ReentrantLock ;p Ublic class Threethreadprinter {private Lock Threadlock = new Reentrantlock ();p rivate int flag = 0;int count = 10; Thread athread = new Thread (new Runnable () {public void run () {while (true) {//Lock threadlock.lock (); try {if (Count < 1 ) {return;} if (count%3 = = 0) {//Athread task System.out.println ("Athread--" + count); count--;}} catch (Exception e) {//Todo:handle Exception} finally {//release lock Threadlock.unlock ();}}}); Thread bthread = new Thread (new Runnable () {public void run () {while (true) {//Lock threadlock.lock (); try {if (Count < 1 ) {return;} if (count%3 = = 1) {//Athread task System.out.println ("Bthread--" + count); count--;}} catch (Exception e) {//Todo:handle Exception} finally {//release lock Threadlock.unlock ();}}}); Thread cthread = new Thread (new Runnable () {public void run () {while (true) {//Lock threadlock.lock (); try {if (Count < 1 ) {return;} if (count%3 = =2) {//Athread task System.out.println ("Cthread--" + count); count--;}} catch (Exception e) {//Todo:handle Exception} finally {//release lock Threadlock.unlock ();}}}); public void Starttwothread () {Athread.start (); Bthread.start (); Cthread.start ();} public static void Main (string[] args) {Threethreadprinter twothreadprinter = new Threethreadprinter (); Twothreadprinter.starttwothread ();}}

Output results

Bthread---10aThread---9cThread---8bThread---- -3cThread-2bThread-1



Java n threads take turns printing numbers problem

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.