多线程

有2中方法可以来创建线程:

  • 继承Thread类
  • 用一个类实现Runnable接口
    具体如下:
package com.qingke.thread;

public class LeannThread {
    public static void main(String[] args) {
        Thread code = new Code();
        code.setName("编写");
        Print print = new Print();
        Thread pr = new Thread(print, "打印机");
        code.start();
        pr.start();
    }

}

class Code extends Thread {
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.println(this.getName() + ":" + "小明在写第" + i + "行代码");

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("代码写完!");

    }
}

class Print implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <= 15; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + "小明在打印第" + i + "页材料");

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("打印完!");
    }

}

在对于像银行账户的需要同步的问题上,现在有一个例子:
一对夫妻在银行有一个共同的账户,则需要用到同步使得账户中的余额保持同步。
如下:

package com.qingke.thread;

public class BankThread {
    public static void main(String[] args) {
        BankAccount count = new BankAccount();
        Thread husband = new BankedThread(count);
        Thread wife = new BankedThread(count);
        husband.start();
        wife.start();
    }

}

class BankAccount {
    private double balance = 1000;

    public /*synchronized*/boolean deposit(double newAdd) {
        if (balance <= 0) {
            return false;
        } else {
            synchronized (this) {
                System.out.println("当前余额为" + balance);

                balance += newAdd;

                System.out.println("当前余额为" + balance);
            }
            return true;
        }
    }
}

class BankedThread extends Thread {
    private BankAccount bankAccount;

    public BankedThread(BankAccount count) {
        bankAccount = count;
    }

    public void run() {
        bankAccount.deposit(200);
    }
}

在上述代码中synchronized 可以直接放在方法声明上,也可以写在方法块内synchronized(obj){} * ** obj*表示需要同步的对象。


模拟一种场景,假设有一个生产商Producer和一个消费者Consumer,另外有一个容器Box,Box中只能放一样东西。若Box为空,则要等Producer生产出来再放到Box中,在通知Consumer。若Box中不空,则需要等Consumer拿完,在通知Producer。
代码如下:

package com.qingke.thread;

public class LearnThreadCommunication {
    public static void main(String[] args) {
        Box box = new Box();
        Thread producer = new Producer(box);
        Thread consumer = new Consumer(box);
        producer.start();
        consumer.start();

    }
}

class Box {
    public int boxValue = 0;
}

class Producer extends Thread {
    private Box box;

    public Producer(Box box) {
        this.box = box;
    }

    public void run() {
        for (int i = 1; i < 6; i++) {

            synchronized (box) {
                while (box.boxValue != 0) {
                    try {
                        System.out.println("Producer: Box是满的,等待");
                        box.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                box.boxValue = i;
                System.out.println("Producer: Box中放入了" + i + ",并通知其他等待者");
                box.notify();
            }
        }
    }
}

class Consumer extends Thread {
    private Box box;

    public Consumer(Box box) {
        this.box = box;
    }

    public void run() {
        for (int i = 1; i < 6; i++) {

            synchronized (box) {
                while (box.boxValue == 0) {
                    try {
                        System.out.println("Consumer: Box是空的,等待");
                        box.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                box.boxValue = 0;
                System.out.println("Consumer: Box中取出了" + i + ",并通知供应者");
                box.notify();
            }
        }
    }
}

用到Object的 wait()notify()方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • synchronized是Java中的关键字,是一种同步锁。它修饰的对象有以下几种: 修饰一个代码块,被修饰的代码...
    明教de教主阅读 682评论 0 2
  • 该文章转自:http://blog.csdn.net/evankaka/article/details/44153...
    加来依蓝阅读 7,381评论 3 87
  • Java多线程学习 [-] 一扩展javalangThread类 二实现javalangRunnable接口 三T...
    影驰阅读 2,987评论 1 18
  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 2,494评论 1 15
  • 写在前面的话: 这篇博客是我从这里“转载”的,为什么转载两个字加“”呢?因为这绝不是简单的复制粘贴,我花了五六个小...
    SmartSean阅读 4,792评论 12 45