java concurrent (1) - 传统线程互斥和通信
编程技术  /  houtizong 发布于 3年前   51
synchronized(obj) { // code block}synchronized(this) { // code block}
synchronized(CurrentClass.class) { // code block}
public synchronized void warranty() { // code segment}public synchronized void merchantability() { // code segment}
public class TraditionalConcurrentCommunication {public static void main(String[] args) {// Ensure to operate the same objectfinal Cooperation cooperation = new Cooperation();// Main threadnew Thread(new Runnable() {@Overridepublic void run() {for (int t = 1; t <= 40; t++) {try {cooperation.first(t);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();// Sub threadnew Thread(new Runnable() {@Overridepublic void run() {for (int t = 1; t <= 40; t++) {try {cooperation.second(t);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}static class Cooperation {private boolean bFirst = true;public synchronized void first(int times) throws InterruptedException {while (!bFirst) { // 使用状态标志防止伪唤醒wait(); // 在当前对象上等待被唤醒}for (int i = 1; i <= 100; i++) {System.out.println(Thread.currentThread().getName() + " is executing first() in loop of " + i+ " of the " + times + " times");}bFirst = false;notify(); // 通知在当前对象上等待的线程,即Sub thread}public void second(int times) throws InterruptedException {while (bFirst) {wait();}for (int i = 1; i <= 10; i++) {System.out.println(Thread.currentThread().getName() + " is executing second() in loop of " + i+ " of the " + times + " times");}bFirst = true;notify(); // 通知在当前对象上等待的线程,即Main thread}}}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接