栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

1.题目:主线程执行10次,子线程执行10次,此过程重复50次

代码:

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.四个线程,共享一个变量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();
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号