每个对象都有一内置锁
wait方法 释放对象锁(不占对象锁)
sleep方法不释放对象锁(占对象锁)
优秀写法 (下面写法可能有问题,synchronized (LOCK) 提到 while前面就好了)
1 class Info { 2 String printStr = "i think this is ok"; 3 int i = 0; 4 5 public void print() { 6 if (i < printStr.length()) { 7 System.out.println(Thread.currentThread().getName() + " print " 8 + printStr.charAt(i)); 9 i++;10 }11 }12 }13 14 public class main {15 private static Object LOCK = new Object();16 static Info info = new Info(); // 互斥资源17 static boolean flag = false; // false for a ,true for b18 19 public static void main(String[] args) {20 // 两个线程 交替打印字符串21 Thread a = new Thread() {22 public void run() {23 while (info.i < info.printStr.length())24 synchronized (LOCK) {25 {26 if (false == flag) {27 try {28 LOCK.wait();// 在wait后的瞬间线程b得到锁29 } catch (InterruptedException e) {30 e.printStackTrace();31 }32 }33 flag = false;34 info.print();35 LOCK.notify();// 在这里虽然唤醒了另一个线程b,但锁并没有释放36 }37 }38 };39 };40 Thread b = new Thread() {41 public void run() {42 while (info.i < info.printStr.length())43 synchronized (LOCK) {44 {45 if (true == flag) {46 try {47 LOCK.wait();// 在wait后的瞬间线程b得到锁48 } catch (InterruptedException e) {49 e.printStackTrace();50 }51 }52 flag = true;53 info.print();54 LOCK.notify();// 在这里虽然唤醒了另一个线程b,但锁并没有释放55 }56 }57 };58 };59 a.start();60 b.start();61 }62 63 }
代码1
1 package ThreadTest; 2 3 4 class Info 5 { 6 String printStr="i think this is ok"; 7 int i=0; 8 boolean flag=false; 9 public void print1()10 {11 synchronized(this)12 {13 if(flag==false)14 {15 try {16 this.wait();17 } catch (InterruptedException e) {18 e.printStackTrace();19 }20 }21 realprint();22 flag=false;23 notify();24 }25 }26 public void print2()27 {28 synchronized(this)29 {30 if(flag==true)31 {32 try {33 this.wait();34 } catch (InterruptedException e) {35 e.printStackTrace();36 }37 }38 realprint();39 flag=true;40 notify();41 }42 }43 public void realprint()44 {45 if(i
代码2
1 package MyThreadMethod; 2 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 class Info 7 { 8 String printStr="i think this is ok"; 9 int i=0; 10 public void print1() 11 { 12 if(i
3 不同写法
1 class Info 2 { 3 String printStr="i think this is ok"; 4 int i=0; 5 public void print() 6 { 7 if(i