java 两个线程按顺序输出字符
2022/6/27 14:20:24
本文主要是介绍java 两个线程按顺序输出字符,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
方法一:
public class threadDemo { public static void main(String[] args) { final Object o=new Object(); final char[] nums="1234567".toCharArray(); final char[] chars="ABCDEFG".toCharArray(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { synchronized (o){ for(char num:nums){ System.out.println(num); o.notify(); o.wait(); } o.notify(); } } }).start(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { synchronized (o){ for(char ch:chars){ System.out.println(ch); o.notify(); o.wait(); } o.notify(); } } }).start(); } }
方法二:
public class threadDemo { static Thread t1=null,t2=null; public static void main(String[] args) { final char[] nums="1234567".toCharArray(); final char[] chars="ABCDEFG".toCharArray(); t1=new Thread(new Runnable() { @Override public void run() { for(char num:nums){ System.out.println(num); LockSupport.unpark(t2); LockSupport.park(); } } }); t2=new Thread(new Runnable() { @Override public void run() { for(char num:chars){ LockSupport.park();//挂起 System.out.println(num); LockSupport.unpark(t1);//叫醒 } } }); t1.start(); t2.start(); } }
方法三:
public class threadDemo { public static void main(String[] args) { final char[] nums="1234567".toCharArray(); final char[] chars="ABCDEFG".toCharArray(); final Lock reentrantLock = new ReentrantLock(); final Condition condition = reentrantLock.newCondition(); new Thread(new Runnable() { @Override public void run() { reentrantLock.lock();//相当synchronized for(char num:nums){ System.out.println(num); condition.signal();//相当于notify try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } condition.signal(); } }).start(); new Thread(new Runnable() { @Override public void run() { reentrantLock.lock(); for(char num:chars){ System.out.println(num); try { condition.signal(); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } condition.signal(); } }).start(); } }
这篇关于java 两个线程按顺序输出字符的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程
- 2024-11-26Springboot单体架构搭建资料详解与实战教程
- 2024-11-26Springboot框架资料:新手入门教程
- 2024-11-26Springboot企业级开发资料入门教程
- 2024-11-26SpringBoot企业级开发资料详解与实战教程
- 2024-11-26Springboot微服务资料:新手入门全攻略