写2个线程,其中一个线程打印 1~ 52,另一个线程打印A~Z, 打印顺序应该是12A34B56C···5152Z。
- 重入锁方式
package ThreadTest;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Hm1 {
public static void main(String [] args){
printt printt = new printt();
Thread th1 = new Thread(new Num(printt));
//设置优先级 数字先输出
th1.setPriority(6);
Thread th2 = new Thread(new ZiM(printt));
th1.start();
th2.start();
}
}
class printt{
Lock lock = new ReentrantLock();
Condition la = lock.newCondition();
Condition lb = lock.newCondition();
public void Num(){
lock.lock();
try {
for(int i =1 ;i<53;i++)
{
System.out.print(i);
if(i%2==0)
{
lb.signalAll();
la.await();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void ZiM(){
lock.lock();
try {
for(int i=65 ;i<91;i++){
System.out.print((char)i);
la.signalAll();
lb.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
class Num implements Runnable{
private printt printt;
Num(printt printt){
this.printt = printt;
}
@Override
public void run() {
this.printt.Num();
}
}
class ZiM implements Runnable{
private printt printt;
ZiM(printt printt){
this.printt = printt;
}
@Override
public void run() {
this.printt.ZiM();
}
}
- synchronized方式
package ThreadTest;
public class Hm2 {
public static void main(String[] args) {
Hm2 hm2 = new Hm2();
new Thread(new SuZi(hm2)).start();
new Thread(new ZiMu(hm2)).start();
}
}
class SuZi implements Runnable{
private Hm2 hm2;
SuZi(Hm2 hm2){
this.hm2 = hm2;
}
@Override
public void run() {
synchronized (this.hm2){
for(int i =1 ;i<53;i++)
{
System.out.print(i);
if(i%2==0)
{
try {
hm2.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
hm2.notify();
}
}
}
}
class ZiMu implements Runnable{
private Hm2 hm2;
ZiMu(Hm2 hm2){
this.hm2 = hm2;
}
@Override
public void run() {
synchronized (this.hm2){
for(int i=65 ;i<91;i++){
System.out.print((char)i);
hm2.notify();
try {
hm2.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
- 结果
12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z
疯狂Java讲义多线程练习题