赞
踩
模拟12306买票过程
共享资源,并发(线程安全)
Web12306.java
- /**
- * 共享资源,并发(线程安全)
- * @author Administrator
- *
- */
- public class Web12306 implements Runnable{
- //票数
- private int ticketNums=99;
-
- @Override
- public void run() {
- while(true) {
- if(ticketNums<0) {
- break;
- }
- // try {
- // Thread.sleep(200); //相当于网络延时问题。会造成数据的不准确性
- // } catch (InterruptedException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- System.out.println(Thread.currentThread().getName()+"--->"+ticketNums--);
- }
- // TODO Auto-generated method stub
-
- }
- public static void main(String[] args) {
- //一份资源
- Web12306 web=new Web12306();
- System.out.println(Thread.currentThread().getName());
- //多个代理
- new Thread(web,"马畜").start();
- new Thread(web,"码农").start();
- new Thread(web,"码蝗").start();
- }
- }
模拟龟兔赛跑的过程
Racer.java
- /**
- * 模拟龟兔赛跑
- * @author Administrator
- *
- */
- public class Racer implements Runnable{
- private String winner; //胜利者
- @Override
- public void run() {
- for(int steps=1;steps<=100;steps++) {
- //模拟兔子休息
- if(Thread.currentThread().getName().equals("rabbit")&&steps%10==0) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName()+"--->"+steps);
- //比赛是否结束
- boolean flag=gameOver(steps);
- if(flag) {
- break;
- }
- }
-
- }
- private boolean gameOver(int steps) {
- if(winner!=null) {//存在胜利者
- return true;
- }else {
- if(steps==100) {
- winner=Thread.currentThread().getName();
- System.out.println("winner==>"+winner);
- return true;
- }
- }
- return false;
- }
- public static void main(String[] args) {
- Racer racer=new Racer();
- new Thread(racer,"tortoise").start();
- new Thread(racer,"rabbit").start();
- }
- }
小结: 两种线程创建方式的比较
继承Thread类方式的多线程
• 优势:编写简单
• 劣势:无法继承其它父类实现Runnable接口方式的多线程
• 优势:可以继承其它类,多线程可共享同一个Runnable对象
• 劣势:编程方式稍微复杂,如果需要访问当前线程,需要调用Thread.currentThread()方法
静态代理例子
StaticProxy.java
- /**
- * 静态代理
- * 公共接口:
- * 1.真实角色
- * 2.代理角色
- * @author Administrator
- *
- */
- public class StaticProxy {
- public static void main(String[] args) {
- new WeddingCompany(new You()).happyMarry();
- // new Thread(线程对象).start();
- }
-
- }
- interface Marry{
- void happyMarry();
- }
- //真实角色
- class You implements Marry{
- @Override
- public void happyMarry() {
- System.out.println("you and 嫦娥终于奔月啦……");
- }
- }
- //代理角色
- class WeddingCompany implements Marry{
- //真实角色
- private Marry target;
- public WeddingCompany(Marry target) {
- this.target=target;
- }
- @Override
- public void happyMarry() {
- ready();
- this.target.happyMarry();
- after();
- }
- private void ready() {
- System.out.println("布置猪窝。。。。。");
- }
- private void after() {
- System.out.println("闹玉兔。。。。。。");
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。