Java face test--4 threads two threads each time to J 1 additional two threads to J each reduce 1

Source: Internet
Author: User

Method One

public class ThreadTest1 {
private int J;
public static void Main (String args[]) {
ThreadTest1 tt = new ThreadTest1 ();
INC INC = Tt.new Inc. ();
Dec Dec = tt.new Dec ();
for (int i = 0; i < 2; i++) {
Thread t = new Thread (inc);
T.start ();
t = new Thread (DEC);
T.start ();
}
}

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);
}

Class Inc implements Runnable {
public void Run () {
for (int i = 0; i < 5; i++) {
Inc. ();
}
}
}

Class Dec implements Runnable {
public void Run () {
for (int i = 0; i < 5; i++) {
Dec ();
}
}
}
}
Method Two
----------a-------------to write again
public class A {
Jmanager j = new Jmanager ();

public static void Main () {
New A (). Call ();
}

void Call () {
for (int i = 0; i < 2; i++) {
New Thread (New Runnable () {
public void Run () {
while (true) {
J.accumulate ();
}
}
). Start ();
New Thread (New Runnable () {
public void Run () {
while (true) {
J.subtract ();
}
}
). Start ();
}
}
}

Class Jmanager {
private int j = 2;

Public synchronized void Subtract () {
j--;
}

Public synchronized void accumulate () {
j + +;
}

}

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.