线程通信的例子:使用线程交替打印1-100
涉及到的三个方法:
wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器
notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的线程
notifyAll():一旦执行此方法,就会唤醒所有的被wait的线程
*说明:
1.wait() notify() notifyAll() 三个方法必须使用在同步代码块或者同步方法中。
2.wait() notify() notifyAll() 三个方法的调用者必须是同步代码块或者同步方法中的同步监视器
否则报异常:java.lang.IllegalMonitorStateException
3.wait() notify() notifyAll() 定义在Object中。因为同步监视器可以是任何一个对象。定义在Object中可以保证任何对象都能用。
package czh.exer;
/**
* 线程通信的例子:使用线程交替打印1-100
*
* 涉及到的三个方法:
* wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器
* notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的线程
* notifyAll():一旦执行此方法,就会唤醒所有的被wait的线程
*
*
* 说明:
* 1.wait() notify() notifyAll() 三个方法必须使用在同步代码块或者同步方法中。
* 2.wait() notify() notifyAll() 三个方法的调用者必须是同步代码块或者同步方法中的同步监视器
* 否则:java.lang.IllegalMonitorStateException
* 3.wait() notify() notifyAll() 定义在Object中。因为同步监视器可以是任何一个对象
*
*
*
* @author zhCoding
* @create 2020-08-01 23:04
*/
class Number implements Runnable{
private int number = 1;
Object obj = new Object();
@Override
public void run() {
while (true){
synchronized (obj) {
obj.notify();
if (number < 101) {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + ":" + number);
number++;
try {
//使得如下wait()方法的线程进入阻塞状态
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
}
public class CommunicationTest {
public static void main(String[] args) {
Number n1 = new Number();
Thread t1 = new Thread(n1);
Thread t2 = new Thread(n1);
t1.start();
t2.start();
}
}
结果:
当然也可以不用锁完成-使用线程交替打印1-100:
package czh.exer;
/**
* 线程通信的例子
*
* @author zhCoding
* @create 2020-08-01 22:41
*/
class MyThreadd implements Runnable{
private int val = 1;
@Override
public void run() {
// for (int i = 1; i < 101; i++) {
// System.out.println(Thread.currentThread().getName()+":"+i);
// }
while (true){
if (val<101) {
if (val % 2 == 1) {
if (Thread.currentThread().getName() == "one") {
System.out.println(Thread.currentThread().getName() + ":" + val);
val++;
}
} else if (val % 2 == 0) {
if (Thread.currentThread().getName() == "two") {
System.out.println(Thread.currentThread().getName() + ":" + val);
val++;
}
}
}else{
break;
}
}
}
}
public class exer2 {
public static void main(String[] args) {
MyThreadd m1 = new MyThreadd();
Thread t1 = new Thread(m1);
Thread t2 = new Thread(m1);
t1.setName("one");
t2.setName("two");
t1.start();
t2.start();
}
}
结果: