今天一大早起来不知为何不能上网,为了打发时间,只好阅读JAVA编程思想,最近经常编写多线程的东西,所以专门看下了多线程的东西,后半章的内容实在不易理解,通读一遍后决定写个小demo帮助自己理解一下,基础的锁机制.代码如下:
public
class
MutexLock {
public static final MutexLock instance = new MutexLock(); // 互斥实例
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo();
demo.start();
System.out.println( " aa " );
try {
Thread.sleep( 1000 * 10 );
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( " bb " );
synchronized (MutexLock.instance) {
System.out.println( " cc " );
MutexLock.instance.notify();
System.out.println( " dd " );
}
System.out.println( " ee " );
}
}
class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println( " a " );
try {
synchronized (MutexLock.instance) {
System.out.println( " b " );
MutexLock.instance.wait();
System.out.println( " c " );
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( " d " );
}
}
public static final MutexLock instance = new MutexLock(); // 互斥实例
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo();
demo.start();
System.out.println( " aa " );
try {
Thread.sleep( 1000 * 10 );
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( " bb " );
synchronized (MutexLock.instance) {
System.out.println( " cc " );
MutexLock.instance.notify();
System.out.println( " dd " );
}
System.out.println( " ee " );
}
}
class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println( " a " );
try {
synchronized (MutexLock.instance) {
System.out.println( " b " );
MutexLock.instance.wait();
System.out.println( " c " );
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( " d " );
}
}
一次wait和notify的使用练习,嗨,当成学java基础的时候没有学扎实