进程:是正在运行的程序
线程:是进程中的单个顺序控制流,是一条执行路径
多线程的实现方案有两种:
方式1:继承Thread类
为什么要重写run()方法呢?
run()和start()方法的区别?
public class MyThread extends Thread{
@Override
public void run(){
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();
}
}
方式2:实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public class MyRunnableDemo {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
// Thread thread1 =new Thread(myRunnable);
// Thread thread2 =new Thread(myRunnable);
//Thread (Runable target,String name)
Thread thread1 =new Thread(myRunnable,"a");
Thread thread2 =new Thread(myRunnable,"b");
thread1.start();
thread2.start();
}
}
相比继承Thread类,实现Runnable接口的好处
Thread类中设置和获取线程名称的方法
如何获取main()方法所在的线程名称?
System.out.println(Thread.currentThread().getName());
public class MyThread extends Thread {
MyThread(){
}
MyThread(String name){
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":" + i);
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
MyThread myThread1 = new MyThread("线程1");
MyThread myThread2 = new MyThread("线程2");
// myThread1.setName("线程1");
// myThread2.setName("线程2");
myThread1.start();
myThread2.start();
System.out.println(Thread.currentThread().getName());
}
}
线程有两种调度模型
java使用的是抢占式调度模型
加入计算机只有一个CPU,那么CPU在某一个时刻只能执行一条指令,线程只有得到CPU时间片,也就是使用权,才可以执行指令。所以说多线程程序执行是有随机性,因为谁抢到CPU的使用权是不一定的。
Thread类中设置和获取线程优先级的方法:
public class ThreadPriorityDemo {
public static void main(String[] args) {
ThreadPriority threadPriority1 = new ThreadPriority();
ThreadPriority threadPriority2 = new ThreadPriority();
ThreadPriority threadPriority3 = new ThreadPriority();
threadPriority1.setName("线程1");
threadPriority2.setName("线程2");
threadPriority3.setName("线程3");
System.out.println(threadPriority1.getPriority()); //默认5
System.out.println(threadPriority2.getPriority());
System.out.println(threadPriority3.getPriority());
System.out.println(Thread.MIN_PRIORITY); //1
System.out.println(Thread.NORM_PRIORITY); //5
System.out.println(Thread.MAX_PRIORITY); //10
threadPriority1.setPriority(5);
threadPriority2.setPriority(10);
threadPriority3.setPriority(1);
threadPriority1.start();
threadPriority2.start();
threadPriority3.start();
}
}
方法名 | 说明 |
---|---|
static void sleep(long millis) | 使当前正在执行的线程停留(暂停执行)指定的毫秒数 |
void join() | 等待这个线程死亡 |
void setDaemon(boolean on) | 将此线程标记为守护线程,当运行的线程都是守护线程时,Java虚拟机将退出 |
public class ThreadSleep extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadSleepDemo {
public static void main(String[] args) {
ThreadSleep threadSleep1 = new ThreadSleep();
ThreadSleep threadSleep2 = new ThreadSleep();
ThreadSleep threadSleep3 = new ThreadSleep();
threadSleep1.setName("a");
threadSleep2.setName("b");
threadSleep3.setName("c");
threadSleep1.start();
threadSleep2.start();
threadSleep3.start();
}
}
public class ThreadJoinDemo {
public static void main(String[] args) throws InterruptedException {
ThreadJoin threadJoin1 = new ThreadJoin();
ThreadJoin threadJoin2 = new ThreadJoin();
ThreadJoin threadJoin3 = new ThreadJoin();
threadJoin1.setName("a");
threadJoin2.setName("b");
threadJoin3.setName("c");
threadJoin1.start();
threadJoin1.join();
threadJoin2.start();
threadJoin3.start();
}
}
public class ThreadDaemonDemo {
public static void main(String[] args) {
ThreadDaemon threadDaemon1 = new ThreadDaemon();
ThreadDaemon threadDaemon2 = new ThreadDaemon();
threadDaemon1.setName("张飞");
threadDaemon2.setName("关羽");
threadDaemon1.setDaemon(true);
threadDaemon2.setDaemon(true);
threadDaemon1.start();
threadDaemon2.start();
Thread.currentThread().setName("刘备");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
案例卖票:
需求:某电影院目前正在上映国产大片,共有100张票,而它有3个窗口卖票,设计一个程序模拟该电影院卖票
public class SellTicket implements Runnable {
private int tickets = 100;
@Override
public void run() {
while (true) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
出现的问题:
原因:
判断多线程程序是否会有数据安全问题的标准
如何解决多线程安全问题?
如何实现?
锁多条语句操作共享数据,可以使用同步代码实现
synchronized(任意对象){
多条语句操作共享数据的代码
}
同步的好处和弊端:
运行效率
public class SellTicket implements Runnable {
private int tickets = 100; //共享数据
private Object lock = new Object();
@Override
public void run() {
while (true) {
synchronized (lock) {
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
同步方法:就是把synchronized关键字加到方法上
修饰符 synchronized 返回值类型 方法名(方法参数){}
同步方法的的锁对象是什么呢?
同步静态方法:就是把synchronized关键字加到静态方法上
修饰符 static synchronized 返回值类型 方法名(方法参数){}
同步静态方法的的锁对象是什么呢?
public class SellTicket implements Runnable {
private int tickets = 100;
private Object lock = new Object();
private int x = 0;
@Override
public void run() {
while (true) {
if (x % 2 == 0) {
synchronized (this) {
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
} else {
sellTicket();
}
x++;
}
}
private synchronized void sellTicket() {
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
StringBuffer
Vector
Hashtable
虽然我们可以理解同步代码和同步方法的锁对象问题,但是我们并没有直接看到在哪里加上了锁,在哪里释放了锁,为了更清晰的表达如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock
Lock实现提供比使用synchronized方法和语句可以获得更广泛的锁定操作
Lock中提供了获得锁和释放锁的方法
Lock是接口不能直接实例化,这里采用它的实现类ReentrantLock来实例化
ReentrantLock的构造方法
public class SellTicket implements Runnable {
private int tickets = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
lock.lock();
try {
while (true) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
} finally {
lock.unlock();
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
生产者消费者模式是一个十分经典的多线程协作的模式,弄懂生产消费者问题能够让我们对多线程编程的理解更加深刻,所谓生产者消费者问题,实际上主要包含了两类线程:
为了解耦生产者和消费者的关系,通常会采用共享的数据区域,就像是一个仓库
为了体现生产者和消费者过程中的等待和唤醒,Java就提供了几个方法供我们使用,这几个方法在Object类中Object类的等待和唤醒方法:
方法名 | 说明 |
---|---|
void wait() | 导致当前线程等待,直到另一个线程调用该对象的notify()方法或notifyAll()方法 |
void notify() | 唤醒正在等待对象监视器的单个线程 |
void notifyAll() | 唤醒正在等待对象监视器的所有线程 |
public class Box {
private int milk;
private boolean state = false;
public synchronized void put(int milk) {
if (state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.milk = milk;
System.out.println("送奶工将第" + this.milk + "瓶奶放入奶箱");
state = true;
notifyAll();
}
public synchronized void get() {
if (!state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("用户拿到第" + this.milk + "瓶奶");
state = false;
notifyAll();
}
}
public class Producer implements Runnable{
private Box box;
public Producer(Box box) {
this.box = box;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
box.put(i);
}
}
}
public class Customer implements Runnable{
private Box box;
public Customer(Box box) {
this.box = box;
}
@Override
public void run() {
while (true){
box.get();
}
}
}
public class BoxDemo {
public static void main(String[] args) {
Box box = new Box();
Producer producer = new Producer(box);
Customer customer = new Customer(box);
Thread thread1 =new Thread(producer);
Thread thread2 =new Thread(customer);
thread1.start();
thread2.start();
}
}
运行结果:
送奶工将第1瓶奶放入奶箱
用户拿到第1瓶奶
送奶工将第2瓶奶放入奶箱
用户拿到第2瓶奶
送奶工将第3瓶奶放入奶箱
用户拿到第3瓶奶
送奶工将第4瓶奶放入奶箱
用户拿到第4瓶奶
送奶工将第5瓶奶放入奶箱
用户拿到第5瓶奶
每个人的人生都有两条路,一条用心走,叫做梦想;一条用脚走,叫做现实。如果心走得太慢,现实就会苍白;而如果脚走得太慢,梦想就不会高飞。人生的精彩,莫过于心走得很美,且与脚步合一。不忘初心,脚踏实地,你就可以创造独有的精彩。