首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java 学习札记4

2013-10-10 
java 学习笔记4(1)线程的强制运行先看线程强制运行的实例 ,再解释程序中是如何让程序强制运行的public cla

java 学习笔记4

(1)      线程的强制运行

先看线程强制运行的实例 ,再解释程序中是如何让程序强制运行的

public class withdra {          private int totalMoney = 0;          public synchronized void getmoney(int money){                 synchronized(this)              {                  System.out.println("正在执行getmoney()方法!");                 int restmoney =  totalMoney;                restmoney -= money;                 try{                        Thread.sleep(1000);                 }catch (InterruptedException e)                     {                                   e.printStackTrace();                           }                 totalMoney =restmoney;                 System.out.println(Thread.currentThread().getName()+"提取1000元后的余额为:"+totalMoney);              }          }        public void setMoney()          {              this.totalMoney=9999;               System.out.println(Thread.currentThread().getName()+"把存款设置为:"+totalMoney);          }       publicwithdra(int totalmoney) {        this.totalMoney =totalmoney;       } }public class FirThread implements Runnable{       privatewithdra  wd;        publicvoid run() {              wd.getmoney(1000);                   }       publicFirThread(withdra wd)         { this.wd = wd ;}}public class secThread implements Runnable{        privatewithdra  wd;        publicvoid run() {              wd.setMoney();                   }       publicsecThread(withdra wd)         { this.wd = wd ;} } public class TestSyn {       publicstatic void main(String[] args) {              withdrawd = new withdra(4000);              System.out.println("现在的存款为4000");              FirThreadft = new FirThread(wd);              secThreadst = new secThread(wd);              Threadth1 = new Thread(ft,"th1");              Threadth2 = new Thread(ft,"th2");              th1.start();              try{                     Thread.sleep(10);              }catch (InterruptedException e) {                     e.printStackTrace();              }              th2.start();                    } }


热点排行