学习笔记(二)多线程
2016-04-07 15:42
197 查看
多线程机制
多线程是指同时存在几个执行体,按照几条不同的执行线索共同工作的情况,使编程人员很方便的开发出具有多线程功能,能同时处理多个任务的功能强大的应用程序。实现多线程的方式
一、继承Thread类public class People extends Thread {
int timeLength;
Csum sum;
People(String s,int timeLength,Csum sum){
setName(s);
this.timeLength=timeLength;
this.sum=sum;
}
public void run(){
for (int i=1;i<=5;i++){
int m=sum.getSum();
sum.setSum(m+1);
System.out.println("我是"+getName()+",现在的和:"+sum.getSum());
try {
sleep (timeLength);
}catch(InterruptedException e){}
}
}
}
public class Csum {
int sum;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Csum sum = new Csum();
People teacher = new People("老师",200,sum);
People student = new People("学生",200,sum);
teacher.start();
student.start();
}
}
二、实现Runnable接口
public class ThreadTest2 implements Runnable {
private int money = 0;
Thread account,casher;
ThreadTest2(){
account=new Thread(this);
account.setName("account");
casher=new Thread(this);
casher.setName("casher");
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true){
money =money-50;
if(Thread.currentThread()==account){
System.out.println("我是"+account.getName()+",现在有:"+money);
if(money<150){
System.out.println(account.getName()+"进入死亡状态");
return;
}
}
else if(Thread.currentThread()==casher){
System.out.println("我是"+casher.getName()+",现在有:"+money);
if(money<150){
System.out.println(casher.getName()+"进入死亡状态");
return;
}
}
try {
Thread.sleep (800);
}catch(InterruptedException e){}
}
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
public class Bank {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest2 test = new ThreadTest2();
test.setMoney(300);
test.account.start();
test.casher.start();
}
}
相关文章推荐
- 如何获取域名(网址)对应的IP地址
- Android的布局ViewStub
- 6.9.5 qmgr_active_done_3_generic函数:将邮件文件移入deferred队列
- java单例模式详解
- 如何获取域名(网址)对应的IP地址
- oracle 11g不能导出空表的解决方法
- Jquery 判断滚动条到达顶部或底部
- 如何在Linux上安装服务器管理软件Cockpit
- Hibernate验证注解
- 轮播图Viewpager支持手动滑动定时滑动和自动加载图片页数
- 屏幕录制
- 44、如何修改已经创建好的数据库的编码格式
- leetcode189.RotateArray
- 6.9.4 qmgr_active_done_25_generic函数:发送退信或延迟提醒信
- mysql innodb 优化 参数篇
- Android自定义绘制
- JPA Many To Many Duplicate record in join table
- 一个函数看懂View事件分发机制
- activiti自定义流程之Spring整合activiti-modeler5.16实例(九):历史任务查询
- R 语言笔记 频数表和列联表