Code examples of Java threads repeating and manipulating Shared variables

  • 2020-04-01 04:28:47
  • OfStack

1. Title: the main thread executes 10 times, the child thread executes 10 times, and the process repeats 50 times

Code:


package com.Thread.test;

public class ThreadProblem {

 public ThreadProblem() {
 
 final Business bus = new Business();
 new Thread(new Runnable() {
  
  public void run() {
  
  for(int j=0;j<50;j++) {
   
   bus.sub(j);
  }
  }
 }).start();
 
 for(int j=0;j<50;j++) {
  
  bus.main(j);
 }
 }
 class Business {
 
 private boolean tag=true;
 public synchronized void sub(int num) {
  
  if(!tag) {
  
  try {
   this.wait();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }
  for(int i=0;i<10;i++)
  {
  System.out.println("sub thread "+i+",loop "+num+".");
  }
  
  tag=false;
  notify();
 }
 
 public synchronized void main(int num) {
  
  if(tag) {
  
  try {
   this.wait();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }
  for(int i=0;i<10;i++) {
  
  System.out.println("main thread "+i+",loop "+num+".");
  }
  
  tag=true;
  notify();
 }
 }
 
 public static void main(String[] args) {
 
 ThreadProblem problem = new ThreadProblem();
 }
}


2. Four threads share a variable j, in which two threads add 1 to j and two threads subtract 1 from j.

The code is as follows:


package com.Thread.test;
//Implement 4 threads, 2 threads plus 1, 2 threads minus 1
public class Demo1 {

 private static int j=0;
 private A a = new A();
 //The constructor
 public Demo1() {
 
 System.out.println("j The initial value of :"+j);
 for(int i=0;i<2;i++) {
  
  new Thread(new Runnable(){
  
  public void run() {
   
   for(int k=0;k<5;k++){
   a.add1();
   }
  }
  }).start();
  
  new Thread(new Runnable(){
  
  public void run() {
   
    for(int k=0;k<5;k++)
    {
   a.delete1();
    }
  }
  }).start();
 }
 }
 class A {
 
 public synchronized void add1() {
  
  j++;
  System.out.println(Thread.currentThread().getName()+" right j add 1 And now j="+Demo1.j);
 }
 
    public synchronized void delete1() {
  
  j--;
  System.out.println(Thread.currentThread().getName()+" right j Reduction of 1 And now j="+Demo1.j);
 }
 }
 
 //Main function for testing
 public static void main(String[] args) {
 
 Demo1 demo = new Demo1();
 }
}


Related articles: