------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
要了解线程,必须得知道什么是进程
1. 进程
进程:是一个正在执行中的程序。
每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者叫一个控制单元。
2. 线程
线程:就是进程中的一个独立的控制单元。
线程在控制着进程的执行。
一个进程中至少有一个线程
3. 线程的创建方式
创建线程的第一种方式:继承Thread类。
步骤:
1,定义类继承Thread。
2,复写Thread类中的run方法。
目的:将自定义代码存储在run方法。让线程运行。
3,调用线程的start方法,
该方法两个作用:启动线程,调用run方法。
//线程的创建方式一,继承Thread类
class Demo extends Thread {
public void run() {
for (int x = 0; x < 60; x++)
System.out.println("demo run----" + x);
}
}
class Test {
public static void main(String[] args) {
Demo d = new Demo();// 创建好一个线程。
d.start();
for (int x = 0; x < 60; x++)
System.out.println("Hello World!--" + x);
}
}
/*
结论:
发现运行结果每一次都不同。
因为多个线程都获取cpu的执行权。cpu执行到谁,谁就运行。
明确一点,在某一个时刻,只能有一个程序在运行。(多核除外)
cpu在做着快速的切换,以达到看上去是同时运行的效果。
我们可以形象把多线程的运行行为在互相抢夺cpu的执行权。
这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,cpu说的算。
*/
创建线程的第二种方式:实现Runable接口
步骤:
1,定义类实现Runnable接口
2,覆盖Runnable接口中的run方法。
将线程要运行的代码存放在该run方法中。
3,通过Thread类建立线程对象。
4,将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。
为什么要将Runnable接口的子类对象传递给Thread的构造函数。
因为,自定义的run方法所属的对象是Runnable接口的子类对象。
所以要让线程去指定指定对象的run方法。就必须明确该run方法所属对象。
5,调用Thread类的start方法开启线程并调用Runnable接口子类的run方法。
实现方式和继承方式有什么区别呢?
实现方式好处:避免了单继承的局限性。
在定义线程时,建立使用实现方式。
两种方式区别:
继承Thread:线程代码存放Thread子类run方法中。
实现Runnable,线程代码存在接口的子类的run方法。
//创建线程的第二种方式:实现Runable接口
class Ticket implements Runnable// extends Thread
{
private int tick = 100;
public void run() {
while (true) {
if (tick > 0) {
System.out.println(Thread.currentThread().getName()
+ "....sale : " + tick--);
}
}
}
}
class Test {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);// 创建了一个线程;
Thread t2 = new Thread(t);// 创建了一个线程;
Thread t3 = new Thread(t);// 创建了一个线程;
Thread t4 = new Thread(t);// 创建了一个线程;
t1.start();// 启动t1线程
t2.start();
t3.start();
t4.start();
}
}
4. 多线程的特征
多线程的安全问题:
问题的原因:
当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,
另一个线程参与进来执行。导致共享数据的错误。
解决办法:
对多条操作共享数据的语句,只能让一个线程都执行完。在执行过程中,其他线程不可以参与执行。
Java对于多线程的安全问题提供了专业的解决方式。
就是同步代码块。
synchronized(对象)
{
需要被同步的代码
}
对象如同锁。持有锁的线程可以在同步中执行。
没有持有锁的线程即使获取cpu的执行权,也进不去,因为没有获取锁。
关于锁的说明:
只要的同一个对象就可以,一般会用类名.class加锁,因为该锁在内存中是唯一的
同步的前提:
1,必须要有两个或者两个以上的线程。
2,必须是多个线程使用同一个锁。
必须保证同步中只能有一个线程在运行。
好处:解决了多线程的安全问题。
弊端:多个线程需要判断锁,较为消耗资源,
//加锁后的代码
class Ticket implements Runnable {
private int tick = 100;
public void run() {
while (true) {
synchronized (this) {
if (tick > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "....sale : " + tick--);
}
}
}
}
}
class Test {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
同步产生的死锁问题:
/*
死锁。
同步中嵌套同步。
如:A中持有B中的锁,
B中又持有A中的锁,
这样容易引起死锁
*/
class Ticket implements Runnable {
private int tick = 1000;
Object obj = new Object();
boolean flag = true;
public void run() {
if (flag) {
while (true) {
synchronized (obj) {
show();
}
}
} else
while (true)
show();
}
public synchronized void show()// this
{
synchronized (obj) {
if (tick > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()
+ "....code : " + tick--);
}
}
}
}
class Test {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (Exception e) {
}
t.flag = false;
t2.start();
}
}
生产者与消费者的问题
class Test {
public static void main(String[] args) {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();// t1 生产者
t2.start();// t2生产者
t3.start();// t3消费者
t4.start();// t4消费者
}
}
/*
* 对于多个生产者和消费者。 为什么要定义while判断标记。 原因:让被唤醒的线程再一次判断标记。 为什么定义notifyAll, 因为需要唤醒对方线程。
* 因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。
*/
class Resource {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
while (flag)
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者.."
+ this.name);
flag = true;
this.notifyAll();
}
// t3 t4
public synchronized void out() {
while (!flag)
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}// t3(放弃资格) t4(放弃资格)
System.out.println(Thread.currentThread().getName() + "...消费者........."
+ this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable {
private Resource res;
Producer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.set("+商品+");
}
}
}
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.out();
}
}
}
JDK1.5 提供的同步问题的新解决方式
/*
JDK1.5 中提供了多线程升级解决方案。
将同步Synchronized替换成现实Lock操作。
将Object中的wait,notify notifyAll,替换了Condition对象。
该对象可以Lock锁 进行获取。
该示例中,实现了本方只唤醒对方操作。
好处: 实现的是显示加锁功能,而且一个锁可以对于多少个condition,方便使用
Lock:替代了Synchronized
lock
unlock
newCondition()
Condition:替代了Object wait notify notifyAll
await();
signal();
signalAll();
*/
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Test {
public static void main(String[] args) {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource {
private String name;
private int count = 1;
private boolean flag = false;
// t1 t2
private Lock lock = new ReentrantLock();
//一个锁可以绑定多个condition
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name) throws InterruptedException {
lock.lock();
try {
while (flag)
condition_pro.await();// t1,t2
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者.."
+ this.name);
flag = true;
condition_con.signal();
} finally {
lock.unlock();// 释放锁的动作一定要执行。
}
}
// t3 t4
public void out() throws InterruptedException {
lock.lock();
try {
while (!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()
+ "...消费者........." + this.name);
flag = false;
condition_pro.signal();
} finally {
lock.unlock();
}
}
}
class Producer implements Runnable {
private Resource res;
Producer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
try {
res.set("+商品+");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
try {
res.out();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}