1.获取对象锁
2.使用 wait和notify执行(通过对象锁),唤醒其他线程 ,关闭当前线程
3.循环操作2个线程
实例:
package com.wu.threadDemo;
public class PrintDemo {
public static void main(String[] args) {
public static void main(String[] args) {
//2个对象锁
Object A = new Object();
Object B = new Object();
Object A = new Object();
Object B = new Object();
//线程传参:打印出不同内容,对象锁也改变
PrintDemo p = new PrintDemo();
print a = p.new print(A,B,"A");
print b = p.new print(B,A,"B");
PrintDemo p = new PrintDemo();
print a = p.new print(A,B,"A");
print b = p.new print(B,A,"B");
Thread a1 = new Thread(a);
Thread a2 = new Thread(b);
a1.start();
a2.start();
}
class print implements Runnable{
Object self;
Object next;
String str;
public String getStr() {
return str;
}
public print(Object self, Object next, String str) {
super();
this.self = self;
this.next = next;
this.str = str;
}
super();
this.self = self;
this.next = next;
this.str = str;
}
public void run() {
while(true)
{
synchronized (self) {
synchronized (next) {
System.out.println(this.getStr());
next.notify();
}
try {
self.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
while(true)
{
synchronized (self) {
synchronized (next) {
System.out.println(this.getStr());
next.notify();
}
try {
self.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}