Synchronized
来源:互联网 发布:jre windows x64.exe 编辑:程序博客网 时间:2024/04/28 22:12
package com.Thread;/* * synchronized(Object) * 同步时object对象必须是同一个 */public class TraditionalSynchronized { public static void main(String[] args){ new TraditionalSynchronized().init(); } public void init(){ final OutPuter outPuter = new OutPuter(); //注意静态方法里面(比如main)不能创建内部类,解决办法:实例化外部类对象,对象调用方法 new Thread(new Runnable(){ public void run(){ while(true){ outPuter.output("zengjinhuaihahahahahahahahhahahaahhahahah"); } } }).start(); new Thread(new Runnable(){ public void run(){ while(true){ OutPuter.output2("zhourui"); } } }).start(); } static class OutPuter{ public void output(String name){ int len = name.length(); // 不知道能不能同步 synchronized(OutPuter.class){ //this和output1同步,OutPuter.class和output2同步 (静态方法,以字节码文件作为句柄,字节码文件是一份) for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }/* public synchronized void output1(String name){ int len = name.length(); for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ static synchronized void output2(String name){ int len = name.length(); for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
0 0
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- synchronized
- 通信系统为何调制和解调(第三次作业)
- C++中string的trim实现函数
- #1141 : 二分·归并排序之逆序对(归并排序)
- T001-UT001-0005
- 黑马程序员——Java基础查找算法:顺序查找和二分查找
- Synchronized
- 统计字符次数
- 体验OpenGL新版本
- android菜鸟之button事件的三种方式
- 鉴别毒水问题
- hdu 3001 Travelling 三进制状压Dp
- 空杯心态,重新出发
- (stl)Valid Pattern Lock
- [Practical.Vim(2012.9)].Drew.Neil.Tip28 学习摘要