源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java线程重复执行以及操作共享变量的代码示例

  • 时间:2020-04-08 07:38 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java线程重复执行以及操作共享变量的代码示例
1.题目:主线程执行10次,子线程执行10次,此过程重复50次 代码:
package com.Thread.test;
/*
 * function:主线程执行10次,子线程执行10次,
 * 此过程重复50次
 */
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.四个线程,共享一个变量j,其中两个线程对j加1,两个线程对j减1。 代码如下:
package com.Thread.test;
//实现4个线程,两个线程加1,两个线程减1
public class Demo1 {

 private static int j=0;
 private A a = new A();
 //构造函数
 public Demo1() {
 
 System.out.println("j的初始值为:"+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()+"对j加1,目前j="+Demo1.j);
 }
 
    public synchronized void delete1() {
  
  j--;
  System.out.println(Thread.currentThread().getName()+"对j减1,目前j="+Demo1.j);
 }
 }
 
 //用于测试的主函数
 public static void main(String[] args) {
 
 Demo1 demo = new Demo1();
 }
}

  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部