Java:写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z。
生活随笔
收集整理的這篇文章主要介紹了
Java:写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫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() {@Overridepublic void run() {for(int i =0;i<26;i++){try{print.printNumber();}catch(InterruptedException e){e.printStackTrace();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {for(int i =0;i<26;i++){try{print.printChar(i);}catch(InterruptedException e){e.printStackTrace();}}}}).start();}}?
總結
以上是生活随笔為你收集整理的Java:写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA多线程:线程创建过程以及生命周期
- 下一篇: Java:假设车库有3个车位(可以通过b