版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/84063111
写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z
多线程编程:使用Runnable接口实例创建线程。使用线程等待方法wait();
package com.java疯狂讲义;
public class Print {
//flag==true时,打印数字;
private boolean flag = true;
//要打印数字的起始数
private int num = 0;
public synchronized void printNumber() throws InterruptedException {
if (!flag) {
this.wait();
}
for (int i = 0; i < 2; i++) {
System.out.println(++num + "\t");
}
flag = false;
this.notify();
}
public synchronized void printChar(int i) throws InterruptedException {
if (flag) {
this.wait();
}
System.out.println((char)('A' + i )+ "\t");
flag = true;
this.notify();
}
}
测试类:
package com.java疯狂讲义;
public class Test {
public static void main(String[] args){
Print print = new Print();
new Thread(new Runnable() {
@Override
public void run() {
for(int i =0;i<26;i++){
try{
print.printNumber();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i =0;i<26;i++){
try{
print.printChar(i);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
}
}