读书人

java多线程小结(一)

发布时间: 2012-09-23 10:28:11 作者: rapoo

java多线程总结(一)

点我进入【多线程理论篇】

java中的多线程

在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

对于直接继承Thread的类来说,代码大致框架是:

class Info {         public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }     public int getAge() {        return age;    }     public void setAge(intage) {        this.age = age;    }     public synchronized voidset(String name, int age){        if(!flag){            try{                super.wait();            }catch (Exception e) {                e.printStackTrace();            }        }        this.name=name;        try{            Thread.sleep(100);        }catch (Exception e) {            e.printStackTrace();        }        this.age=age;        flag=false;        super.notify();    }         public synchronized voidget(){        if(flag){            try{                super.wait();            }catch (Exception e) {                e.printStackTrace();            }        }                 try{            Thread.sleep(100);        }catch (Exception e) {            e.printStackTrace();        }        System.out.println(this.getName()+"<===>"+this.getAge());        flag=true;        super.notify();    }    private String name = "Rollen";    private int age = 20;    private boolean flag=false;} /** * 生产者 * */class Producer implements Runnable {    private Info info = null;     Producer(Info info) {        this.info = info;    }     public void run() {        boolean flag = false;        for (int i =0; i < 25; ++i) {            if (flag) {                                 this.info.set("Rollen",20);                flag = false;            } else {                this.info.set("ChunGe",100);                flag = true;            }        }    }} /** * 消费者类 * */class Consumer implements Runnable {    private Info info = null;     public Consumer(Info info) {        this.info = info;    }     public void run() {        for (int i =0; i < 25; ++i) {            try {                Thread.sleep(100);            } catch (Exception e) {                e.printStackTrace();            }            this.info.get();        }    }} /** * 测试类 * */class hello {    public static void main(String[] args) {        Info info = new Info();        Producer pro = new Producer(info);        Consumer con = new Consumer(info);        new Thread(pro).start();        new Thread(con).start();    }}

【程序运行结果】:Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20ChunGe<===>100Rollen<===>20先在看结果就可以知道,之前的问题完全解决。


原文链接:http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html

读书人网 >编程

热点推荐