zoukankan      html  css  js  c++  java
  • java基础-多线程执行

    package Thanqi;
    
    public class TestApple implements Runnable{
        
        //苹果的数量
        private int count = 5;
        
        //拿苹果
        //synchronized 线程同步关键字
        private  void getapple()
        {
    
            synchronized (this){
            if(count<=0)
            {
                System.out.println(Thread.currentThread().getName()+"没有苹果了");
                return;
            }
            count--;
            
            System.out.println(Thread.currentThread().getName()+"拿了一个苹果,苹果还剩"+count);
            
            
        }}
        
        public void run()
        {
            //连续拿苹果
            while(count>0)
            {
                getapple();
    //            try {
    //                Thread.sleep(500);
    //            } catch (InterruptedException e) {
    //                // TODO 自动生成的 catch 块
    //                e.printStackTrace();
    //            }
            }
            
    //        for(int i= 0;count>0;i++)
    //        {
    //            
    //        }
            
        }
    
    }
    package Thanqi;
    
    public class Test05 {
        
        public static void main(String[] args){
            
            //测试线程同步
            //强苹果
            TestApple ta= new TestApple();
            
            //第一个线程 小明
            
            Thread t1 = new Thread(ta);
            t1.setName("小明");
            
            t1.start();
            
            Thread t2= new Thread(ta,"小强");
            t2.start();
            
            
        }
    }
  • 相关阅读:
    《图解CSS3》笔记5 媒体与Responsive设计
    理论篇 前端MVC、MVP、MVVM思考1
    AngularJS篇 $resource使用笔记
    《图解CSS3》笔记4 animation动画
    Prim
    邻接矩阵与邻接表
    差分约束
    SPFA
    floyd
    Kosaraju
  • 原文地址:https://www.cnblogs.com/zs6666/p/5919675.html
Copyright © 2011-2022 走看看