黑马程序员_多线程

来源:互联网 发布:vb format函数怎么用 编辑:程序博客网 时间:2024/06/08 17:07

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------


多线程有多种实现方法,包括继承Thread类,实现Runnable接口,以及在交通灯视频里看到的新方法。线程分安全不安全,安全的线程一半内部会同步代码块,使用synchronized把要同步的代码块放入其中,而同步的锁是一个对象。当放在方法没有指定锁时,默认的锁为该类的字节码对象。

package Test;

//利用多线程,模拟售票系统,同时有4个窗口进行售票

 

public class ThreadDemo {

       publicstatic void main(String[] args){

              //创建对象

              threadTestt= new threadTest();

              //对同一对象创建4个线程

              newThread(t).start();

              newThread(t).start();

              newThread(t).start();

              newThread(t).start();    

       }

}

 

class threadTest implements Runnable{

       //定义售票总数

       privateint ticket=100;

       Stringstr=new String("");

       //覆写run方法

       publicvoid run(){

              while(true){

                     //同步代码块,避免多线程错误

                     synchronized(str){

                            if(ticket>0)

                            {

                                   try{

                                          System.out.println(Thread.currentThread().getName()+

                                                        "  saling "+ticket--);

                                   }

                                  

                                   catch(Exceptione){

                                          e.printStackTrace();

                                   }

                            }

                     }

              }

       }

}



---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------


0 0
原创粉丝点击