Java线程重复执行以及操作共享变量的代码示例
时间:2021-09-11 08:09:25|栏目: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();
}
}
上一篇:mybatis-plus IdWorker生成的Id和返回给前台的不一致的解决
栏 目:JAVA代码
下一篇:spring中使用Mockito解决Bean依赖树问题方法
本文地址:http://www.codeinn.net/misctech/174199.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




