JavaSE 多线程 Part2

来源:互联网 发布:php addslashes 编辑:程序博客网 时间:2024/06/10 06:40

–原作者:尚硅谷-佟刚


package com.atweihai.thread;/** * 利用多线程:交替打印字母a-z  * */public class PrintLetters  implements Runnable{    char ch='a';    public synchronized void  print (){            //防止打印字母z后面的字符            if(ch<='z'){                 System.out.println(Thread.currentThread().getName() +": "+ ch);                 ch++;                  notify();                 try {                        wait();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                 }    }    @Override    public void run() {        while(ch<='z'){            print();        }    }    public static void main(String[] args) {        PrintLetters printLetters=new PrintLetters();        Thread th1=new Thread(printLetters);        Thread th2=new Thread(printLetters);        th1.setName("线程-1");        th2.setName("线程-2");        th1.start();        th2.start();    }}

原创粉丝点击