java 多线程

example 1:
/**
 * Created by Administrator on 2016/8/31 0031.
 */

public class ThreadLearn implements Runnable{
    private String name;
    public ThreadLearn(String name){
        this.name = name;
    }
    public void run(){
        for(int i = 0; i < 100; i++){
            System.out.println(name + ":" + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String [] args) {
        ThreadLearn t1 = new ThreadLearn("t1");
        ThreadLearn t2 = new ThreadLearn("t2");
        new Thread(t1).start();
        new Thread(t2).start();
    }
}
 
 
 
 
example  2:
 
class Info {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public synchronized void set(String name, int age){
        this.name=name;
        try{
            Thread.sleep(100);
        }catch (Exception e) {
            e.printStackTrace();
        }
        this.age=age;
    }

    public synchronized void get(){
        try{
            Thread.sleep(100);
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(this.getName()+"<===>"+this.getAge());
    }
    private String name = "Rollen";
    private int age = 20;
}

/**
 * 生产者
 * */
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(new Producer(new Info())).start();
        new Thread(con).start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值