Design four threads. Two threads increase 1 for j each time, and the other two threads decrease 1 for j each time. Write the program 100 times in a loop.

Source: Internet
Author: User

Design four threads. Two threads increase 1 for j each time, and the other two threads decrease 1 for j each time. Write the program 100 times in a loop.

Package cn. usst. DataTest6;/*** four threads are designed. Two threads increase 1 to j each time, and the other two threads decrease 1 to j each time. Write the program 100 times in a loop. * @ **/Public class DataTest6 {private int j; public static void main (String [] args) {DataTest6 dt = new DataTest6 (); Inc inc = dt. new Inc (); Dec = dt. new Dec (); for (int I = 0; I <2; I ++) {Thread t = new Thread (inc); t. start (); t = new Thread (dec); t. start () ;}} class Inc implements Runnable {public void run () {for (int I = 0; I <100; I ++) {inc ();}}} class Dec implements Runnable {public void run () {for (int I = 0; I <100; I ++) {dec () ;}} private synchronized void inc () {j ++; System. out. println (Thread. currentThread (). getName () + "+ inc:" + j);} private synchronized void dec () {j --; System. out. println (Thread. currentThread (). getName () + "-dec:" + j );}}

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.