三个线程A,B,C,每个线程将自己在屏幕上打印五边,打印顺序为ABCABCABC....
class Print{
private int flag=1; //1表示A,2表示B,3表示C
private int count=0;
public int getCount(){
return count;
}
public synchronized void PrintA(){
while(flag!=1){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag=2;
notifyAll();
count++;
}
public synchronized void PrintB(){
while(flag!=2){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag=3;
notifyAll();
count++;
}
public synchronized void PrintC(){
while(flag!=3){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag=1;
notifyAll();
count++;
}
}
class MyThread implements Runnable {
private Print print;
public MyThread(Print print) {
this.print = print;
}
@Override
public void run() {
while (print.getCount() < 13) { //调用A的次数 count
if (Thread.currentThread().getName().equals("A")) {
print.PrintA();
}else if (Thread.currentThread().getName().equals("B")) {
print.PrintB();
}else if(Thread.currentThread().getName().equals("C")) {
print.PrintC();
}
}
}
}
public class Main{
public static void main(String[] args) {
Print print=new Print();
MyThread mythread=new MyThread(print);
new Thread(mythread,"A").start();
new Thread(mythread,"B").start();
new Thread(mythread,"C").start();
}
}
两个线程,一个打印数字1-52,一个打印字母A-Z,打印顺序为12A34B56C....
class Print{
private boolean flag=true; //信号量
private int count=1;
public synchronized void PrintNum(){
if(flag==false){ //等待
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print(2*count-1);
System.out.print(2*count);
flag=false; //执行打印字母方法
notify(); //唤醒打印字母线程
}
public synchronized void PrintChar(){
if(flag==true){ //等待
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print((char)('A'+count-1));
flag=true; //执行打印数字方法
count++;
notify(); //唤醒打印数字线程
}
}
public class haha{
public static void main(String[] args) {
Print print=new Print();
//打印数字线程
new Thread(() ->{ //匿名内部类
for(int i=0;i<26;i++){
print.PrintNum();
}
}).start();
//打印字母线程
new Thread(()->{
for(int i=0;i<26;i++){
print.PrintChar();
}
}).start();
}
}