JavaSE 多线程 Part1

来源:互联网 发布:mac dns设置成什么值 编辑:程序博客网 时间:2024/06/06 00:27

–原作者:尚硅谷-佟刚


package com.atweihai.thread;public class ShareApple implements Runnable{    private int appleCount=5;    //获取苹果的同步方法    public synchronized boolean getApple(){                if(appleCount>0){                    appleCount--;                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    System.out.println(Thread.currentThread().getName()+"拿走了一个苹果,还剩下 "+                            appleCount+"个苹果.");                    return true;                }                return false;    }    //线程体    @Override    public void run() {        boolean flag=getApple();        while(flag){            flag=getApple();        }        System.out.println(Thread.currentThread().getName()+"线程结束.");    }        public static void main(String[] args) {            ShareApple sa=new ShareApple();            Thread th1=new Thread(sa);            Thread th2=new Thread(sa);            th1.setName("小明");            th2.setName("小强");            th2.start();            th1.start();        }}
原创粉丝点击