Java代码 synchronized _A synchronized _A_02

  1. package cn.itcast;
  2.  
  3. public class TraditionalThreadSynchronized {
  4. public static void main(String[] args) {
  5. new TraditionalThreadSynchronized().init();
  6. }
  7.  
  8. private void init() {
  9. final Outputer outputer = new Outputer();
  10.  
  11. new Thread(new Runnable() {
  12.  
  13. @Override
  14. public void run() {
  15. outputer.outputString("这是一个测试!!!");
  16. }
  17. }).start();
  18.  
  19. new Thread(new Runnable() {
  20.  
  21. @Override
  22. public void run() {
  23. outputer.outputString("This is a test!!!");
  24. }
  25. }).start();
  26. }
  27.  
  28. /*要保证两个方法及两个方法以上的代码同步性,必须用同一个对象作为同步代码块的锁*/
  29. /*要想实现方法互斥分组,就是通过synchronized(obj)中的obj的不同来完成的*/
  30. static class Outputer {
  31. /*
  32. * 也可以把整个方法作为同步代码块
  33. * 像这样public synchronized void outputString(String name)
  34. */
  35. public void outputString(String name) {
  36.  
  37. while (true) {
  38. /*非静态方法的同步锁是this对象*/
  39. synchronized (this) {
  40. for (int i = 0; i < name.length(); i++) {
  41. System.out.print(name.charAt(i));
  42. }
  43. }
  44. System.out.println();
  45. }
  46. }
  47.  
  48. public void outputString2(String name) {
  49. while (true) {
  50. /*任何一个对象都可以作为同步代码块的锁*/
  51. synchronized (new Object()) {
  52. for (int i = 0; i < name.length(); i++) {
  53. System.out.print(name.charAt(i));
  54. }
  55. }
  56. System.out.println();
  57. }
  58. }
  59.  
  60. public static void outputString3(String name) {
  61.  
  62. while (true) {
  63. /*静态方法的同步锁是类的字节码对象*/
  64. synchronized (Outputer.class) {
  65. for (int i = 0; i < name.length(); i++) {
  66. System.out.print(name.charAt(i));
  67. }
  68. }
  69. System.out.println();
  70. }
  71. }
  72. }
  73. }