黑马程序员_多线程
来源:互联网 发布: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>、期待与您交流! ----------------------
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 黑马程序员_多线程
- 修改AngularJS中的$http cache中的数据
- poj3308 Paratroopers --- 最小点权覆盖->最小割
- hadoop学习之第二个程序求平均成绩。
- cocos2d-x 事件分发机制 ——触摸事件监听
- cocos2d-x 事件分发机制 ——加速计事件监听
- 黑马程序员_多线程
- XML的SelectNodes使用方法以及XPath
- 20 Copy Clone
- hdu1627
- Linux(Ubuntu) 下 SecureCRT 7 30天循环破解
- 计算机就业方向
- Invalid location of tag 解决办法分析
- 【足迹C++primer】58、Template Parameter
- 判断两条线段/直线相交,并求交点