用三个线程循环输出ABC
前两天看Java吧有人求助这个问题。想了想并不是很难。今天就顺手实现了一下。
我自己想到的有两种方法,一个是使用synchronized,一个是使用lock。
一、synchronized
package com.test;
public class PrintABC {
private static int count = 0;
public static void main(String[] args) {
String str = "ABC";
PrintABC printABC = new PrintABC();
ThreadA threadA = printABC.new ThreadA(str);
ThreadB threadB = printABC.new ThreadB(str);
ThreadC threadC = printABC.new ThreadC(str);
threadA.start();
threadB.start();
threadC.start();
}
/**
* 打印A
* @author LKB
*
*/
class ThreadA extends Thread{
private String str;
public ThreadA(String str) {
// TODO Auto-generated constructor stub
this.str = str;
}
public void run(){
while(count < 28){
synchronized (str) {
if(count%3 == 0){
System.out.println("A");
count++;
}
}
}
}
}
/**
* 打印B
* @author LKB
*
*/
class ThreadB extends Thread{
private String str;
public ThreadB(String str) {
// TODO Auto-generated constructor stub
this.str = str;
}
public void run(){
while(count < 29){
synchronized (str) {
if(count%3 == 1){
System.out.println("B");
count++;
}
}
}
}
}
/**
* 打印C
* @author LKB
*
*/
class ThreadC extends Thread{
private String str;
public ThreadC(String str) {
// TODO Auto-generated constructor stub
this.str = str;
}
public void run(){
while(count < 30){
synchronized (str) {
if(count%3 == 2){
System.out.println("C");
System.out.println("++++++");
System.out.println("------");
count++;
}
}
}
}
}
}
这个方法的关键是synchronized关键字的位置。把它放在while判断之下就OK了。如果把synchronized关键字放在while外,则一直在锁中无法跳出锁。
二、lock
package com.test; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class PrintABC2 { private int count = 0;
private Lock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
private Condition conditionC = lock.newCondition(); public static void main(String[] args) {
PrintABC2 printABC = new PrintABC2();
ThreadA threadA = printABC.new ThreadA();
ThreadB threadB = printABC.new ThreadB();
ThreadC threadC = printABC.new ThreadC();
threadA.start();
threadB.start();
threadC.start(); } /**
* 打印A
* @author LKB
*
*/
class ThreadA extends Thread{ public void run(){
try {
lock.lock();
while(count < 30){
if (count%3 != 0) {
conditionA.await();
}
System.out.println("A");
count ++;
conditionB.signalAll();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
lock.unlock();
System.out.println("ThreadA 中执行了 unlock");
}
}
} /**
* 打印B
* @author LKB
*
*/
class ThreadB extends Thread{ public void run(){
try {
lock.lock();
while(count < 30){
if (count%3 != 1) {
conditionB.await();
}
System.out.println("B");
count ++;
conditionC.signalAll();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
lock.unlock();
System.out.println("ThreadB 中执行了 unlock");
}
}
} /**
* 打印C
* @author LKB
*
*/
class ThreadC extends Thread{ public void run(){
try {
lock.lock();
while(count < 30){
if (count%3 != 2) {
conditionC.await();
}
System.out.println("C");
System.out.println("+++++++");
System.out.println("-------");
count ++;
if(count < 30){
conditionA.signalAll();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
lock.unlock();
System.out.println("ThreadC 中执行了 unlock");
}
}
} }
lock方法相对而言就简单多了,不需要精妙地设计,只需要知道lock和condition的用法就好了。
在一个lock对象里可以创建多个Condition(即对象监视器)实例。线程对象可以注册到指定的Condition中,从而可以有选择性地进行线程通知。
用三个线程循环输出ABC的更多相关文章
- 使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束
简要分析: 要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中.同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来 ...
- java Semaphore实现ABC三个线程循环打印
Semaphore位于java.util.concurrent包下.其中有两个重要的方法acquire()和release().acquire用来获取一个信号量,并且是阻塞型的,如果当前还有可用的信号 ...
- Java多线程:用三个线程控制循环输出10次ABC
转载:http://www.cnblogs.com/gaopeng527/p/5257884.html 题目:有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C,要求, 同时启动三个 ...
- Java多线程循环打印ABC的5种实现方法
https://blog.csdn.net/weixin_39723337/article/details/80352783 题目:3个线程循环打印ABC,其中A打印3次,B打印2次,C打印1次,循环 ...
- java面试记录二:spring加载流程、springmvc请求流程、spring事务失效、synchronized和volatile、JMM和JVM模型、二分查找的实现、垃圾收集器、控制台顺序打印ABC的三种线程实现
注:部分答案引用网络文章 简答题 1.Spring项目启动后的加载流程 (1)使用spring框架的web项目,在tomcat下,是根据web.xml来启动的.web.xml中负责配置启动spring ...
- java中使用ReentrantLock锁中的Condition实现三个线程之间通信,交替输出信息
本文直接附上源代码,如下是自己写的一个例子 面试题需求: 使用Condition来实现 三个线程 线程1 线程2 线程3 三个交替输出 [按照 线程1(main)-->线程2-->线程3] ...
- C#中添加三个线程同时启动执行某一方法,并依次调用某方法中的循环打印输。
添加三个线程同时启动执行某一方法,并依次调用某方法中的打印输:ABC ABC ABC ABC 实现代码如下: using System; using System.Collections.Generi ...
- 斐讯面试记录—三线程交替打印ABC
package cn.shenzhen.feixun; public class PrintABC extends Thread{ private String name; private Objec ...
- 三个线程abc顺序执行
1.使用synchronized悲观锁(秋招阿里的一个笔试题,应该写的比较复杂,然后就没有然后了o(╥﹏╥)o) public class ThreadThreadp { private int fl ...
随机推荐
- codeforces 876 C. Classroom Watch
http://codeforces.com/contest/876/problem/C C. Classroom Watch time limit per test 1 second memory l ...
- nginx目录路径重定向[转]
如果希望域名后边跟随的路径指向本地磁盘的其他目录,而不是默认的web目录时,需要设置nginx目录访问重定向. 应用场景:dashidan.com/image自动跳转到dashidan.com/fol ...
- 【BZOJ4237】稻草人 [分治][单调栈]
稻草人 Time Limit: 40 Sec Memory Limit: 256 MB[Submit][Status][Discuss] Description JOI村有一片荒地,上面竖着N个稻草 ...
- 在eclipse安装mybatis的插件
1.在help中打开 2.搜索mybatipse 3:功能简介 1:要查找某一个方法 在dao接口中某一个方法中 按住 Ctrl键 鼠标指到方法名称上 选择open xml 就会自动跳转 ...
- Spring Boot中对log4j进行多环境不同日志级别的控制
之前介绍了在<Spring boot中使用log4j记录日志>,仅通过log4j.properties对日志级别进行控制,对于需要多环境部署的环境不是很方便,可能我们在开发环境大部分模块需 ...
- IE6透明PNG解决方案
IE6不支持PNG-24图片一直困扰很多人,但是可以通过IE的独有的滤镜来解决,解决的方案很多,比如:将滤镜写在CSS里,还可以写成单独的 Javascript文件,本来认为推荐两种做法:第一种,将所 ...
- Linux kernel kfifo分析【转】
转自:https://zohead.com/archives/linux-kernel-kfifo/ 本文同步自(如浏览不正常请点击跳转):https://zohead.com/archives/li ...
- python基础===基于cv2的播放器
import cv2 import threading import win32gui,win32con class Producer(threading.Thread): ""& ...
- MySQL登录问题1045 (28000)处理步骤【原创】
MySQL登录问题1045 (28000) 俩台服务器主从复制,从的同步账号无法远程登录主服务器.报错ERROR 1045 (28000): Access denied for user 'root ...
- 苹果容器超出内容overflow滑动卡顿问题
-webkit-overflow-scrolling:touch; 就这么一段代码,加载需要滚动的容器css样式中.因为苹果的硬件加速产生的后果....