package com; public class TraditionalThreadSynchronizeTest { public static void main(String[] args) { new TraditionalThreadSynchronizeTest().init(); } public void init() { final Output output = new Output(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } output.output("zhangxiaoxiang"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } output.output2("lihuoming"); } } }) .start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } output.output3("lihuoming"); } } }) .start(); } static class Output { public void output(String name) { int len = name.length(); synchronized (Output.class) { //synchronized (this) { for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } } public synchronized void output2(String name) { int len = name.length(); // synchronized (Output.class) { //synchronized (this) { for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); //} System.out.println(); } } public static synchronized void output3(String name) { int len = name.length(); // synchronized (Output.class) { //synchronized (this) { for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); //} System.out.println(); } } } }
代码量提升之路 - 线程同步与互斥
原创
©著作权归作者所有:来自51CTO博客作者foxspark的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:代码量提升之路 - 定时器
下一篇:代码量提升之路 - 线程间通信
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
代码量提升之路-Java多线程
Java多线程的实现方式有两种: 继承Thread类成为其子类并覆写run方法,实现Runnable接口并实现run方法。两种方式各种所长。
Java 多线程 thread public -
linux线程同步(1)-互斥量
一.概述 互斥量是线程同步的一种机制,用来保护多线程的共享资源。同一时刻
互斥量 临界区 #include -
线程互斥与同步案例
一共有100个盒子,每个盒子中有一定数量的能量,每个线程持有一个盒子,
多线程编程 java 线程 Math System -
代码量提升之路 - 接口练习
代码量提升之路
接口练习 代码量提升之路 -
代码量提升之路 - 线程范围内共享变量
线程范围内的数据共享 通过两个模块取得​
private import public