面试题 设计四个线程

本文探讨如何设计四个线程,其中两个负责将变量j递增,另外两个负责将变量j递减,重点在于线程同步和并发控制。
摘要由CSDN通过智能技术生成

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1

package day2;

public class TestThreads {
	private int j = 1;
 
	// 加线程
	private class Inc implements Runnable {
		public void run() {
			for (int i = 0; i < 10; i++) {
				inc();
			}
		}
	}
 
	// 减线程
	private class Dec implements Runnable {
		public void run() {
			for (int i = 0; i < 10; i++) {
				dec();
			}
		}
	}
 
	// 加1
	private synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName() + "-inc:" + j);
	}
 
	// 减1
	private synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName() + "-dec:" + j);
	}
 
	// 测试程序
	public static void main(String[] args) {
		TestThreads test = new TestThreads();
		// 创建两个线程类
		Thread thread = null;
		Inc inc = test.new Inc();
		Dec dec = test.new Dec();
		// 启动4个线程
		for (int i = 0; i < 2; i++) {
			thread = new Thread(inc);
			thread.start();
			thread = new Thread(dec);
			thread.start();
		}
	}
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值