多线程例子
package com.knowledge.Test;/** * 继承Thread类 * @author job * */public class syn_gou extends Thread{ //余额 int yu; //总金额 int count = 1000; //每次索取金额 int getmoney = 200; //run方法是Thread类的线程执行体 public void run(){ //实现同步(没有同步则每次线程取钱混乱) synchronized(this){ //如果总金额大于等于所取金额向下执行 if(count >= getmoney){ //计算余额 yu = count - getmoney; //改变取完后的金额 count = yu; System.out.println(Thread.currentThread().getName()+"取钱余额:"+getmoney+"余额为:"+yu); }else{ System.out.println("余额不足!"); } } }} package com.knowledge.Test;/** * 测试类 * @author job * */public class syn_test { public static void main(String[] args){ //syn_gou类的实例 syn_gou s = new syn_gou(); //创建6条线程 Thread t = new Thread(s); Thread t1 = new Thread(s); Thread t2 = new Thread(s); Thread t3 = new Thread(s); Thread t4 = new Thread(s); Thread t5 = new Thread(s); //启动线程 t. start(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); //启动的这6个线程具体先执行那个是系统内部来控制,在程序中我们不能控制 //具体那个先执行是看那个先抢占到cpu,先抢到的先执行。所以会出现测试结果中的 /* Thread-1 Thread-3 Thread-2 Thread-5 Thread-4 也可以理解为随机的 */ }}