我们知道,并发的编程在企业中用的很多,对于并发的学习是很重要的。
现在我们想从程序上给大家一个分析,在我写这个程序的时候,只知道wait()是线程等待,
notify是唤醒线程,还有一个notifyAll是唤醒所有线程,一般情况下 我们为了保险起见,会用notifyAll来唤醒我们的线程的。
但是,你是真的理解这个意思么,下面我们来看一个程序吧。
main类
package endual;
public class MainApp {
public static void main(String[] args) {
Query q = new Query(0) ;
Query1 q1 = new Query1(0) ;
Thread thread = new Thread(new Thread1(q)) ;
Thread thread2 = new Thread(new Thread2(q)) ;
Thread thread3 = new Thread(new Thread3(q1)) ;
thread.start() ;
thread2.start() ;
thread3.start() ;
}
}
Query1类
package endual;
public class Query1 {
private int value = 7;
private boolean isFlag = false ;
public Query1(int value) {
//this.value = value ;
}
public synchronized void getValue() {
try {
wait() ; //如果有人叫他,那么他会唤醒,然就执行下面的程序了
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("-------------------------------------------") ;
}
}
query类
package endual;
public class Query {
private int value = 7;
private boolean isFlag = false ;
public Query(int value) {
//this.value = value ;
}
public synchronized void getValue() {
if (!isFlag) { //如果是正确的
isFlag = true ;
notifyAll() ;
}
try {
wait() ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("我是线程1" + (value++)) ;
}
public synchronized void setValue() {
if (!isFlag) { //如果是正确的
try {
wait() ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isFlag = false ;
value-- ;
System.out.println("我是线程2" + value) ;
notifyAll() ;
}
}
很显然,上面有的方法是notifyAll这个意思就是说唤醒所有等待的线程了。
三个线程:
package endual;
public class Thread1 implements Runnable{
private Query q = null ;
public Thread1(Query q) {
this.q = q ;
}
public void run() {
while (true) {
q.getValue() ;
}
}
}
--------------------------------------------
package endual;
public class Thread2 implements Runnable{
private Query q = null ;
public Thread2(Query q) {
this.q = q ;
}
public void run() {
while (true) {
q.setValue() ;
}
}
}
-------------------------------------
package endual;
public class Thread3 implements Runnable{
private Query1 q1 = null ;
public Thread3(Query1 q1) {
this.q1 = q1 ;
}
public void run() {
while (true) {
q1.getValue() ;
}
}
}
请问,打印的结果中会出现------------------------------------------------------------------
这个么?