方法1: wait,notify, synchronized
package com.hnist.lzn.thread;
public class PrintThread {
/*
写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z。
打印顺序为12A34B56C……5152Z。
*/
static boolean index = true;
static String str = "A";
static class A implements Runnable{
int i = 1;
@Override
public void run() {
synchronized (str){
while(i <= 52){
if(index){
System.out.println(i++);
System.out.println(i++);
index = !index;
str.notify();
}else{
try{
str.wait();
}catch (Exception e){
}
}
}
}
}
}
static class B implements Runnable{
int i = 0;
@Override
public void run() {
synchronized(str){
while(i < 26){
if(!index){
System.out.println((char)(str.charAt(0)+i++));
index = !index;
str.notify();
}else{
try{
str.wait();
}catch (Exception e){
}
}
}
}
}
}
public static void main(String[] args) {
Thread th1 = new Thread(new A());
Thread th2 = new Thread(new B());
th1.start();
th2.start();
}
}
方法二:ReentrantLock condition
package com.hnist.lzn.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Condition {
/*
写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z。
打印顺序为12A34B56C……5152Z。
用Conditon 实现
*/
static Lock lock = new ReentrantLock();
static java.util.concurrent.locks.Condition printcondi = lock.newCondition();
static java.util.concurrent.locks.Condition printChar = lock.newCondition();
static boolean index = true;
static String str = "A";
static class PrintNumber implements Runnable{
int i = 1;
@Override
public void run() {
lock.lock();
try{
while(i <= 52)
{
if(index){
System.out.println(i++);
System.out.println(i++);
index = !index;
printChar.signal();
}else{
printcondi.await();
}
}
}catch (Exception e){
}finally {
lock.unlock();
}
}
}
static class PrintChar implements Runnable{
int i = 0;
@Override
public void run() {
lock.lock();
try{
while(i < 26){
if(!index){
System.out.println((char)(str.charAt(0)+i));
i++;
index = !index;
printcondi.signal();
}else{
printChar.await();
}
}
}catch (Exception e){
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
Thread th1 = new Thread(new PrintNumber());
Thread th2 = new Thread(new PrintChar());
th1.start();
th2.start();
}
}