一個java多線程面試題

來源:互聯網
上載者:User

標籤:nts   not   runnable   ati   run   business   adt   log   資源   

線程a 列印 數字 0--12;

線程b 列印 字母 a--z;

列印結果:0ab1cd2ef3gh4ij5kl6mn7op8qr9st10uv11wx12yz

要求用到 線程間傳值;

分析:線程a列印一個數字,線程b列印兩個字母 , 進行13次迴圈,

通過公用資源類進行線程間傳值

public class FftThreadTest {
public static void main(String[] args) {//建立final資來源物件final Business business = new Business();char c=‘a‘;
for(int i=0;i<=12;i++){final char a= c;business.pringtInt(i);business.setC(a);new Thread(new Runnable() {@Overridepublic void run() {business.pringtString();}}).start();c=(char)((int)c+2);}}}/**
業務類:1列印數字,2列印字母,
**/class Business {private boolean isInt=true; //標記是否列印數字private char c; //要列印的字母
//列印數字 同步鎖public synchronized void pringtInt(int i){
//如果不是數字等待while(!isInt){try {wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.print(i);
//修改標記isInt=false;this.notify(); //喚醒等待線程}
//列印字母 同步鎖public synchronized void pringtString(){
//如果是數字等待while(isInt){try {wait();} catch (InterruptedException e) {e.printStackTrace();}}
//列印兩個字母for(int i=0;i<2;i++){System.out.print(c);c++;}
//修改標記isInt=true;this.notify(); //喚醒等待線程}public void setC(char c){ this.c=c; }}

  

一個java多線程面試題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.