Java多线程的学习代码

使用继承Thread的方式来创建多线程

package mutilthreading;

/*
        创建线程方式一:继承Thread类,重写run方法,调用start开启线程
        线程开启不一定立即执行

        main是主线程,如果运行了run方法,就会先执行完子线程之后才来执行主线程
        如果运行了start方法,线程都会一起执行,没有先后顺序
 */
public class TestThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println("我是子线程");
        }
    }

    public static void main(String[] args) {
        TestThread1 testThread1=new TestThread1();
        testThread1.start();

        for (int i = 0; i < 50; i++) {
            System.out.println("我是主线程");
        }
    }
}

使用实现implements的接口来创建多线程

package mutilthreading;

/*
        创建线程方式二:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,通过创建一个线程对象来调用start开启线程

        比较推荐这种方法,因为一份资源可以分配给多个线程,所以不推荐直接基础Thread类来进行多线程
 */
public class TestThread2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println("我是子线程");
        }
    }

    public static void main(String[] args) {
        //创建一个线程runnable接口实现类对象
        TestThread2 testThread2=new TestThread2();
        //创建线程对象。通过线程对象来开启我们的线程
        Thread thread=new Thread(testThread2);

        thread.start();

        for (int i = 0; i < 50; i++) {
            System.out.println("我是主线程");
        }
    }
}

解决同步安全的实例

package mutilthreading;

public class TestThread3 implements Runnable{
    private int tick=10;

    @Override
    public void run() {
        while (true){
            if (buy()==false) {
                break;
            }
        }

    }

    /*
            同步方法:
            一种是synchronized,线程安全,注意,synchronized只能用在小范围的方法进行修饰,否则就会影响程序的效率
            还有一种是synchronized(变化的量){},锁代码块
     */

    /*
            锁lock
            如果要处理异常,要把lock.unlock()写入到finally中

            private final ReentrantLock lock = new ReentrantLock();

            lock.lock();
            要锁的代码
            lock.unlock();
     */
    public synchronized Boolean buy(){
        if (tick<=0){
            return false;
        }
        System.out.println(Thread.currentThread().getName()+"——》拿到了第"+(this.tick--)+"票");
        return true;
    }

    public static void main(String[] args) {
        TestThread3 testThread3=new TestThread3();
        new Thread(testThread3,"小明").start();
        new Thread(testThread3,"大明").start();
        new Thread(testThread3,"黄牛").start();
    }
}

生产者消费者模型的Java实现

package mutilthreading;

/**
生产者消费者模型
 */
public class ProductionConsumption {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}

//生产者
class Productor extends Thread {

    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了第\t"+i+"\t只鸡");
        }
    }
}

//消费者
class Consumer extends Thread {

    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            Chicken chicken = container.pop();
            System.out.println("消费了第\t"+chicken.id+"\t只鸡");
        }
    }
}

//缓冲区
class SynContainer{
    //容器大小
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    //生产者放入产品
    public synchronized void push(Chicken chicken){
        if(count==chickens.length){
            //满了,通知消费者消费
            try {
                this.wait();//当前线程设置为等待状态
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        chickens[count]=chicken;
        count++;
        this.notifyAll();//唤醒在等待线程
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        if(count==0){
            //没鸡,通知生产者生产
            try {
                this.wait();//当前线程设置为等待状态
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        count--;
        Chicken chicken = chickens[count];

        this.notifyAll();//唤醒在等待线程
        return chicken;
    }
}

class Chicken{
    int id;
    public Chicken(int id) {
        this.id = id;
    }
}

版权声明:本文为weixin_45715461原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。