LeetCode刷题之旅【多线程篇-3】中等: 1115. 交替打印FooBar

JUC练习代码-力扣多线程1115题目:交替打印FooBar,解题详解 题目描述 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print(“foo”); } } public void bar() { for (int i = 0; i < n; i++) { print(“bar”); } } } 两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。 请设计修改程序,以确保 “foobar 阅读详情

2019-11-20 

目录

题目:

解题1

解题2:对象锁

解题3:信号量


题目:

 

解题1


class FooBar {
	private int n;
	private static Object lock = new Object();
	private static volatile Boolean flag = true;

	public FooBar(int n) {
		this.n = n;
	}

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			synchronized (lock){
				if (!flag){
					lock.wait();
				}
				// printBar.run() outputs "bar". Do not change or remove this line.
				printFoo.run();
				flag = false;
				lock.notify();
			}
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			synchronized (lock){
				if (flag){
					lock.wait();
				}
				// printBar.run() outputs "bar". Do not change or remove this line.
				printBar.run();
				flag = true;
				lock.notify();
			}
		}
	}

	public static void main(String[] args) {
		FooBar fooBar = new FooBar(2);
		Runnable runnable1 = new Runnable() {
			@Override
			public void run() {
				try {
					fooBar.foo(new Runnable() {
						@Override
						public void run() {
							System.out.print("foo");
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		Runnable runnable2 =new Runnable() {
			@Override
			public void run() {
				try {
					fooBar.bar(new Runnable() {
						@Override
						public void run() {
							System.out.print("bar");
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		Thread thread1 = new Thread(runnable1);
		thread1.start();
		Thread thread2 = new Thread(runnable2);
		thread2.start();

	}
}
  • 对象同步锁:确保foo和bar方法只会被一个线程执行
  • 线程休眠与唤醒:wait/notify
//对象同步锁用法推荐
synchronized (obj) {
              while (&lt;condition does not hold&gt;)
                  obj.wait();
              ... // Perform action appropriate to condition
          }

解题2:对象锁

分析: 将printFoo操作和printBar操作分别加锁,来保证两者串行发生,设置一个boolean类型变量fooTurn来指明当前操作的轮次,当其为True时,打印foo,当其为False时,打印bar。每个线程在同步代码块内部,判断当前轮次和自己的操作是否符合,若符合,则执行打印操作,若不符合,则放弃锁。

class FooBar {
    private int n;
    private boolean fooTurn = true;
    private Object lock = new Object();
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            
            synchronized(lock) {
                if (!fooTurn) lock.wait();
                fooTurn = false;
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                lock.notifyAll();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            
            synchronized(lock) {
                if (fooTurn) lock.wait();
                fooTurn = true;
                // printBar.run() outputs "bar". Do not change or remove this line.
        	    printBar.run();
                lock.notifyAll();
            }
        }
    }
}

作者:copyreadmachine
链接:https://leetcode-cn.com/problems/print-foobar-alternately/solution/java-suo-by-copyreadmachine/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

解题3:信号量

  • 使用信号量,acquire 就是 值+1
    release 就是 值-1
    简单理解就是当值是0,就可以继续执行,不为零就等待变为0后再执行
public class FooBar {
    private int n;
    //here is the full path, or maybe cann't compile in leetcode.
    java.util.concurrent.Semaphore semaphoreFoo=new java.util.concurrent.Semaphore(0);
    java.util.concurrent.Semaphore semaphoreBar=new java.util.concurrent.Semaphore(0);

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            printFoo.run();
            //由于下面阻塞了,所以这里变为0,下面的方法就能继续执行
            semaphoreBar.release();
            //这里让他等一会,等到bar()执行完
            semaphoreFoo.acquire();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            // 进来先变为1,就会等上面的release()使他变为0,才进行,所以肯定在foo之后。
            semaphoreBar.acquire();
            printBar.run();
            //bar()执行完了,就让foo()继续。
            semaphoreFoo.release();
        }
    }
}

  • Java 并发包中的信号量 Semaphore 实际上是一个功能完毕的计数信号量,从概念上讲,它维护了一个许可集
    合,对控制一定资源的消费与回收有着很重要的意义。Semaphore 可以控制某个资源被同时访问的任务数,它
    通过acquire()获取一个许可,release()释放一个许可。如果被同时访问的任务数已满,则其他 acquire 的任务
    进入等待状态,直到有一个任务被 release 掉,它才能得到许可。
  • 就是 Semaphore 仅仅是对资源的并发访问的任务数进行监控,而不会保证线程安全,因此,在访问的时候,要自己控制线程的安全访问。
MATLAB计算各种复合干热指数,如SDHI、DHMI等 MATLAB编程实现各种复合干热指数 阅读详情

相关推荐

基于STM32的可穿戴式多生理参数实时监测与预警系统

针对传统可穿戴健康设备存在的生理参数监测种类单一、数据处理依赖云端导致响应滞后、续航能力弱等问题,设计一种基于STM32的可穿戴式多生理参数实时监测与预警系统。系统以STM32L476RG低功耗微控制器为核心,集成心率血氧传感器、体温传感器、血压传感器,实现人体心率、血氧饱和度、体温、收缩压/舒张压的同步采集;通过边缘端轻量化数据处理算法完成参数异常判定,结合低功耗硬件设计与软件休眠策略,在保证监测精度的同时延长续航。测试结果表明,系统心率监测误差≤2次/分钟,血氧饱和度误差≤2%,体温误差≤±0.2℃,血

m0_74026776的博客 2039

力扣(LeetCode)刷题,简单+中等题(第36期)

力扣(LeetCode)定期刷题,每期10道题,业务繁重的同志可以看看我分享的思路,不是最高效解决方案,只求互相提升。

不脱发的程序猿 4万+

Word中 Go to endnote 出现闪退问题解决办法

Word中 Go to endnote 出现闪退问题解决办法

努力努力努力 1万+

LangChain v1.0架构解析与LLM应用开发指南

大语言模型(LLM)应用开发框架通过标准化接口简化了AI集成流程。LangChain作为主流框架,其v1.0版本采用三层架构设计:核心层提供LCEL表达式语言实现组件流水线,集成层对接各类LLM和外部系统,应用层封装Chain、Agent等高级抽象。该框架特别适合构建需要工具调用、记忆管理和复杂推理的智能应用,如客服机器人、数据分析助手等场景。新版引入的LangGraph扩展支持更复杂的工作流编排,结合LCEL的管道式编程和Agent的自主决策能力,开发者可以快速实现RAG架构等热门AI应用模式。

weixin_30617737的博客 664

基于STM32设计的校园智慧路灯系统(华为云IOT)(212)

当前设计并研发了基于STM32的智慧路灯系统,本系统的目的是打造一个高效节能、智能化管理的校园照明环境。通过集成STM32F103RCT6高性能微控制器为核心,结合多种传感器模块如BH1750光敏传感器、热释电人体感应模块以及中科微电子GPS模块等,实现了对校园路灯的精准控制与实时监控。

5137

[QMT量化交易小白入门]-四十九、中小盘策略是否还有未来,市值再平衡策略,年化收益率124%

该策略旨在通过定期再平衡持仓,保持投资组合中股票数量恒定(),并优先持有市值较小的股票。具体来说,策略每两天(period = 2)进行一次再平衡,根据当前市值对持仓进行调整,以实现微盘股的投资目标。中小市值策略对资金量要求有限制,资金量太大由于流动性不足,滑点可能较大,资金量太小,可能不能达到10-20只持仓,来分散风险,10-100w可能是比较理想的,后续可以根据波动率动态调仓,或波动率大于一定值时触发再平衡加入ROE或其他财务指标,或者研发投入强度大的专精特新企业,进行组合优化。

木头大左的博客 1184

Leetcode(Java多线程)-1115. 交替打印FooBar

我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { print("bar"); } ...

Slayer_Zhao的博客 467

5、硬件工程师笔试面试——上拉电阻、下拉电阻(2025版本)

本文系统介绍了上拉电阻和下拉电阻的原理与应用。上拉电阻通过连接电源确保电路高电平状态,常用于数字电路防抖、OC门驱动等场景;下拉电阻连接地线维持低电平,适用于低电平触发电路。文章详细分析了两种电阻的选择方法、功耗与响应速度的平衡策略,以及在高速信号传输中的影响差异。同时对比了二者的优缺点,并提供了模拟电路中的应用实例。最后给出了电阻值计算的工程方法,为硬件工程师的电路设计提供了实用参考。

XU157303764的博客 2868

力扣交替打印FooBar

这道题要注意的是两个线程唤醒和等待的顺序,应为第一个线程会比第二个线程更早结束,所以如果第一个线程已经结束,而第二个线程还在等待被唤醒,那第二个线程会一直等待下去,因此第一个线程要先等待后唤醒,这样他会先唤醒第二个线程再结束 语无伦次,直接看代码吧 from threading import Condition, Thread import time def printFoo(): ...

面向对象的笔记 385

在 Windows 11 下运行 OminiParse V2,详细教程【含问题解决细节】

OmniParser V2 是微软推出的 GUI 智能体解析工具,可将屏幕截图转换为结构化元素,帮助 LLM 理解和操作界面。它在检测小图标和推理速度上显著提升,延迟降低 60%,并支持多种 LLM。

简简单单Onlinezuozuo 1090

基于STM32的嵌入式平台实现EtherCAT主站

本文将介绍如何在基于STM32的嵌入式平台上构建EtherCAT主站,并提供相应的源代码。使用SOEM库提供的API函数,我们可以实现与EtherCAT从站设备的实时通信和数据交换。在STM32的代码中,使用SOEM库提供的API函数初始化EtherCAT主站。在SOEM库中,我们可以找到EtherCAT主站的实现代码和相关的API函数。使用SOEM库提供的API函数实现EtherCAT主站的功能,包括发送和接收EtherCAT数据帧、处理从站设备的状态等。确保连接正常并且设备能够相互通信。

CodeSageX的博客 2832

Leetcode多线程编程:交替打印FooBar Python题解

首先,要想写出本题,首先先要理解一个概念,就是Semaphore对象 Semaphore() Semaphore对象内部管理着一个计数器,该计数器由每个acquire()调用递减,并由每个release()调用递增。计数器永远不会低于0,当acquire()发现计数器为0的时候,线程阻塞,等待其他线程调用release()`。 import time import threading def ...

Alkaid的博客 1207

RT-DETR改进策略【Neck】| GFPN 超越BiFPN 通过跳层连接和跨尺度连接改进RT-DETR颈部网络

本文记录的是利用颈部结构优化RT-DETR的目标检测网络模型。利用改进后的颈部网络,通过跳层连接,避免了在进行反向传播时的梯度消失问题,并且引入跨尺度连接,可以实现不同级别和层次的特征充分融合,获取足够的高层语义信息和低层空间信息交换,从而在大规模变化场景下提高检测性能。GIRAFFEDET: A HEAVY-NECK PARADIGM FOR OBJECT DETECTION-GFPN包含了上述的跳层连接(dense-link和log2nlog _{2} nlog2​n-link)以及跨尺度连接(Quee

Limiiiing的博客 2228

leetcode1115. 交替打印 FooBar

两个不同的线程将会共用一个 FooBar 实例:线程 A 将会调用 foo() 方法,而线程 B 将会调用 bar() 方法请设计修改程序,以确保 “foobar” 被输出 n 次。示例 1:输入:n = 1输出:“foobar”解释:这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,“foobar” 将被输出一次。示例 2:输入:n = 2输出:“foobarfoobar”解释:“foobar” 将被输出两次。

weixin_43356308的博客 1298

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Java多线程刷题(LeetCode-1115. 交替打印FooBar)

ACM刷题 Java学习笔记 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { print...

越看越喜欢啊 1329

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

从synchronized到Condition:FooBar交替打印的进阶之路(1115.交替打印)

作为多线程初学者,FooBar问题的进阶解法让我打开了JUC并发编程的大门。的显式控制和Condition的精准唤醒,看似复杂,实则是对机制的优化和延伸。核心知识点回顾:1. 显式锁:ReentrantLock的lock()/unlock(),必须在finally释放;2. 条件队列:Condition的await()/signal(),实现精准线程通信;3. 健壮性:while循环防御虚假唤醒,保证执行顺序稳定;4. 核心逻辑:状态标记控制轮次,锁保证原子性和可见性。如果你也刚学完。

2301_80336940的博客 803

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Leetcode1115交替打印FooBar

交替打印FooBar 1. 题目描述: 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { p...

阿福呀 1340

(多线程)leetcode1115. 交替打印FooBar 记得Thread.yield();

我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { print("bar"); } ...

少说,多做。 9095

[LeetCode 1115] 交替打印FooBar

[LeetCode 1115] 交替打印FooBar 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { print("bar"); } } } 两个不同的线程将会共用一个 FooBar

liuwenyou的博客 376

LeetCode刷题:1115. 交替打印 FooBar(多线程)

synchronized + flag标志位 + wait / notify :(思路:设置一个标志位变量,在两个方法内交替改变标志位的值,然后通过wait / notify控制交替打印)。信号量 Semaphore:(思路:设置两个信号量 Semaphore,在两个方法内交替获取 / 释放,实现交替打印)

想好了就去做吧 即便失败了 至少这条路上留下了你的脚印 756

Leetcode—1115. 交替打印 FooBar【中等】(多线程)

运行结果 之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

Atticus的博客 567

【LeetCode】第1115题——交替打印FooBar(难度:中等)

【LeetCode】第1115题——交替打印FooBar(难度:中等)题目描述解题思路代码详解思路一:使用标志位和yield()思路二:使用阻塞队列BlockingQueue注意点 题目描述 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i &l

Se7en_Dayz的博客 410

LeetCode - 交替打印FooBar

题目链接:https://leetcode-cn.com/problems/print-foobar-alternately/ 题目描述 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void b...

良晨的技术站 579

LeetCode-1115.交替打印FooBar(多线程)

LeetCode 题目描述 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { print("...

2.wa 1065

LeetCode:交替打印【1115】

LeetCode:交替打印【1115】 题目描述 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++)...

weixin_30763455的博客 78

力扣1115.交替打印FooBar

力扣1115.交替打印FooBar 力扣1115.交替打印FooBar 题目: 我们提供一个类: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i &l...

asdfg2001121的博客 347
上一篇: LeetCode刷题之旅【数据库篇-6】 - 中等:178. 分数排名
下一篇: IM即时通信学习总结(2):IM学习基础 - 消息ID严格递增
后台技术汇
博客等级 码龄11年 670粉丝 531原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后台技术汇

对你的帮助,是对我的最好鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值