wait()、notify()
public class Test05 {
public static void main(String[] args) {
MyThread3 mt=new MyThread3();
Thread th=new Thread(mt,"线程一");
th.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (mt) {
mt.notify();
}
}
}
class MyThread3 implements Runnable{
@Override
public void run() {
synchronized (this) {
System.out.println("***进入同步代码块");
try {
wait();
System.out.println("***wait之后重新拿到了锁");
} catch (InterruptedException e) {
System.out.println("***"+Thread.currentThread().getName()+"被打断!");
}
for(int i=1;i<=20;i++){
System.out.println(Thread.currentThread().getName()+"***"+i);
}
System.out.println("***同步代码块执行结束!");
}
}
}
生产者、消费者模型
public class Test06 {
public static void main(String[] args) {
Person person = new Person();
Input in = new Input(person);
Output out = new Output(person);
Thread th1 = new Thread(in,"生产者生产了: ");
Thread th2 = new Thread(out,"消费者消费了: ");
th1.start();
th2.start();
}
}
class Person {
String name;
String sex;
boolean flag = true;
}
class Input implements Runnable {
private Person person;
public Input(Person person) {
this.person = person;
}
@Override
public void run() {
int x = 0;
while (true) {
synchronized (person) {
if (person.flag) {
if (x == 0) {
person.name = "tom";
person.sex = "male";
} else {
person.name = "张三";
person.sex = "女";
}
x = (x + 1) % 2;
person.flag = false;
person.notify();
} else {
try {
person.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Output implements Runnable {
private Person person;
public Output(Person person) {
this.person = person;
}
@Override
public void run() {
while (true) {
synchronized (person) {
if (!person.flag) {
System.out.println(Thread.currentThread().getName()+person.name + "***" + person.sex);
person.flag = true;
person.notify();
} else {
try {
person.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}