//2.写两个线程,一个线程打印1-52,另一个线程答应字母A-Z。
//打印顺序为12A34B56C……5152Z。通过使用线程之间的通信协调关系。
//注:分别给两个对象构造一个对象o,
//数字每打印两个或字母每打印一个就执行o.wait()。在o.wait()之前不要忘了写o.notify()
package homework2;
import com.sun.swing.internal.plaf.synth.resources.synth;
public class Test2 {
public static void main(String[] args) {
Object object = new Object();
shuzi shuzi = new shuzi(object);
zimu zimu = new zimu(object);
Thread t = new Thread(shuzi);
Thread t1 = new Thread(zimu);
t.start();//数字线程先运行
t1.start();
}
}
class shuzi implements Runnable{
private Object object;
//声明类的引用
public shuzi(Object object) {
this.object = object;
}
public void run() {
synchronized (object) {//上锁
for(int i=1;i<53;i++){
System.out.print(i);
if(i%2==0){
object.notifyAll();//唤醒线程
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class zimu implements Runnable{
private Object object;
public zimu(Object object) {
this.object = object;
}
public void run() {
synchronized (object) {
for(int j=65;j<91;j++){
char c = (char)j;
System.out.print(c);
object.notifyAll();
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
方法2:
public class Test {
public static void main(String[] args) {
O o = new O();
A a = new A(o);
B b = new B(o);
Thread t = new Thread(a);
Thread t1 = new Thread(b);
t.start();//数字的线程先运行
t1.start();
}
}
class O{
boolean flag = false;//没有
public synchronized void set() throws InterruptedException{
for(int i=1;i<52;i++){
if(this.flag == true){
this.wait();
}
if(i%2==0){
this.flag=true;
this.notifyAll();
}
System.out.print(i);
}
}
public synchronized void get() throws InterruptedException{
for(int j =65;j<91;j++){
if(this.flag == false){
this.wait();
}
char c = (char)j;
System.out.print(c);
this.flag = false;
this.notify();
}
}
}
class A implements Runnable{
O o = new O();
public A(O o) {
super();
this.o = o;
}
public void run() {
try {
o.set();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class B implements Runnable{
O o = new O();
public B(O o) {
super();
this.o = o;
}
public void run() {
try {
o.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}