多线程交替打印数字和字母

数字从1打印到52, 字母从A打印到Z
例如 12A34B·······

  1. package 酷家乐0913;
  2. public class A {
  3. static class Thread1 implements Runnable{
  4. private int num = 1;
  5. private int step = 1;
  6. private char c = 'A';
  7. @Override
  8. public void run() {
  9. synchronized (this){ // 核心的地方,需要把这个类锁住
  10. while (step<=78){
  11. this.notify(); // 通知需要这个类的线程,开始竞争锁。
  12. if(step%3 ==0){
  13. System.out.print(c++);
  14. step++;
  15. }else {
  16. System.out.print(num++);
  17. step++;
  18. }
  19. try {
  20. Thread.sleep(1);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. try {
  25. this.wait();//释放锁
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. }
  32. }
  33. public static void main(String[] args) {
  34. Thread1 t1 = new Thread1();
  35. new Thread(t1).start();
  36. new Thread(t1).start();
  37. }
  38. }