编写代码:交替输出字母和数字
1.Synchronized加wait,notify操作
需要注意的问题是for循环结束之后必须再写一个o.notify(),如果没有调用这个方法,虽然最后的输出结果可能仍然正确,但最后总有一个线程阻塞在wait()操作而无法结束。出现下面的情况:
代码如下:
package com.demo.util;
public class ThreadUtils {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) {
Object o = new Object();
t1 = new Thread() {
public void run() {
synchronized (o) {
// for(int i=97;i<123;i++) {//小写字母
for (int i = 65; i < 91; i++) {
System.out.print((char) i);
try {
o.notify();//叫醒t2
o.wait();//阻塞自己
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//需要注意,如果不写,会出现一个线程一直阻塞在wait()操作而无法结束,出现输出完成而程序无法结束
o.notify();
}
}
};
t2 = new Thread() {
public void run() {
synchronized (o) {
for (int i = 1; i < 27; i++) {
System.out.print(i + " ");
try {
o.notify();//叫醒t1
o.wait();//阻塞自己
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
o.notify();
}
}
};
t1.start();
t2.start();
}
}
2.使用LockSupport类中的park和unpark方法,park为阻塞当前线程,unpark(Thread thread)为唤醒传入参数所对应线程。
代码如下:
package com.demo.util;
import java.util.concurrent.locks.LockSupport;
public class ThreadUtils {
static Thread t3 = null;
static Thread t4 = null;
public static void main(String[] args) {
t3 = new Thread() {
public void run() {
// for(int i=97;i<123;i++) {//小写字母
for (int i = 65; i < 91; i++) {
System.out.print((char) i);
LockSupport.unpark(t4);//唤醒t4
LockSupport.park();//阻塞自己
}
}
};
t4 = new Thread() {
public void run() {
for (int i = 1; i < 27; i++) {
LockSupport.park();
System.out.print(i);
LockSupport.unpark(t3);
}
}
};
t3.start();
t4.start();
}
}
输出结果如下: