黑马程序员——Java多线程

时间:2023-02-20 10:50:27
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

一、进程与线程

进程:是一个正在执行中的程序。每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者叫一个控制单元。
线程:就是进程中的一个独立的控制单元。线程在控制着进程的执行。
一个进程中至少有一个线程。

Java VM  启动的时候会有一个进程java.exe。该进程中至少一个线程负责java程序的执行。而且这个线程运行的代码存在于main方法中。该线程称之为主线程。
扩展:其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程。

二、自定义线程

1、创建线程的第一种方式:继承Thread类。
通过对API的查找,java已经提供了对线程这类事物的描述。就Thread类。步骤:
1)定义类继承Thread。
2)复写Thread类中的run方法。目的:将自定义代码存储在run方法。让线程运行。
3)调用线程的start方法,该方法两个作用:启动线程,调用run方法。

发现运行结果每一次都不同。因为多个线程都获取CPU的执行权。CPU执行到谁,谁就运行。明确一点,在某一个时刻,只能有一个程序在运行。(多核除外)CPU在做着快速的切换,以达到看上去是同时运行的效果。我们可以形象把多线程的运行行为在互相抢夺CPU的执行权。
这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,CPU说的算。

为什么要覆盖run方法呢?
Thread类用于描述线程。该类就定义了一个功能,用于存储线程要运行的代码。该存储功能就是run方法。也就是说Thread类中的run方法,用于存储线程要运行的代码。

public class Demo extends Thread{
public void run(){
for(int x=0; x<60; x++)
System.out.println("demo run----"+x);
}
}

public class ThreadDemo {
public static void main(String[] args) {
//for(int x=0; x<4000; x++)
//System.out.println("Hello World!");

Demo d = new Demo();//创建好一个线程。
d.start();//开启线程并执行该线程的run方法。
//d.run();//仅仅是对象调用方法。而线程创建了,并没有运行。
for(int x=0; x<60; x++)
System.out.println("Hello World!--"+x);
}
}
练习:创建两个线程,和主线程交替运行。
/*
* 原来线程都有自己默认的名称。Thread-编号 该编号从0开始。
* static Thread currentThread():获取当前线程对象。
* getName(): 获取线程名称。
* 设置线程名称:setName或者构造函数。
*/
public class Test extends Thread{
//private String name;
Test(String name){
//this.name = name;
super(name);
}
public void run(){
for(int x=0; x<60; x++){
System.out.println((Thread.currentThread()==this)+"..."+this.getName()+" run..."+x);
}
}
}

public class ThreadTest {
public static void main(String[] args) {
Test t1 = new Test("one---");
Test t2 = new Test("two+++");
t1.start();
t2.start();
for(int x=0; x<60; x++){
System.out.println("main....."+x);
}
}
}

2、创建线程的第二种方式:实现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方法。

/*
需求:简单的卖票程序。多个窗口同时买票。
*/
public 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--);
}
}
}
}

public class TicketDemo{
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();
}
}

三、多线程安全问题

对上述的售票例子,通过分析,发现,打印出0,-1,-2等错票。多线程的运行出现了安全问题。
问题的原因:1)当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完;2)另一个线程参与进来执行。导致共享数据的错误。
解决办法:对多条操作共享数据的语句,只能让一个线程都执行完。在执行过程中,其他线程不可以参与执行。

Java对于多线程的安全问题提供了专业的解决方式。就是同步代码块。
对象如同锁。持有锁的线程可以在同步中执行。没有持有锁的线程即使获取CPU的执行权,也进不去。

同步的前提:1)必须要有两个或者两个以上的线程。2)必须是多个线程使用同一个锁。
必须保证同步中只能有一个线程在运行。

好处:解决了多线程的安全问题。
弊端:多个线程需要判断锁,较为消耗资源,

public class Ticket implements Runnable{
private int tick = 1000;
Object obj = new Object();
public void run(){
while(true){
synchronized(obj){
if(tick>0){
//try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);
}
}
}
}
}


public class TicketDemo2{
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();
}
}
需求:银行有一个金库。有两个储户分别存300员,每次存100,存3次。
/*
目的:该程序是否有安全问题,如果有,如何解决?
如何找问题:
1,明确哪些代码是多线程运行代码。
2,明确共享数据。
3,明确多线程运行代码中哪些语句是操作共享数据的。
*/

public class Bank{
private int sum;
//Object obj = new Object();
//同步函数
public synchronized void add(int n){
//synchronized(obj)
//{
sum = sum + n;
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("sum="+sum);
//}
}
}

public class Cus implements Runnable{
private Bank b = new Bank();
public void run(){
for(int x=0; x<3; x++){
b.add(100);
}
}
}

public class BankDemo{
public static void main(String[] args) {
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
同步函数用的是哪一个锁呢?
函数需要被对象调用。那么函数都有一个所属对象引用。就是this。所以同步函数使用的锁是this。

如果同步函数被静态修饰后,使用的锁是什么呢?
但通过验证,发现不在是this。因为静态方法中也不可以定义this。
静态进内存,内存中没有本类对象,但是一定有该类对应的字节码文件对象。类名.class  该对象的类型是Class静态的同步方法,使用的锁是该方法所在类的字节码文件对象。 类名.class


死锁。同步中嵌套同步。

四、线程间通信

1、等待唤醒机制wait;notify();notifyAll();
都使用在同步中,因为要对持有监视器(锁)的线程操作。所以要使用在同步中,因为只有同步才具有锁。
为什么这些操作线程的方法要定义Object类中呢?
因为这些方法在操作同步中线程时,都必须要标识它们所操作线程只有的锁,只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒。不可以对不同锁中的线程进行唤醒。也就是说,等待和唤醒必须是同一个锁。而锁可以是任意对象,所以可以被任意对象调用的方法定义Object类中。
public class Res{
private String name;
private String sex;
private boolean flag = false;

public synchronized void set(String name,String sex){
if(flag)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out(){
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"........"+sex);
flag = false;
this.notify();
}
}

public class Input implements Runnable{
private Res r ;
public Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("mike","man");
else
r.set("丽丽","女女女女女");
x = (x+1)%2;
}
}
}

public class Output implements Runnable{
private Res r ;
public Output(Res r){
this.r = r;
}
public void run(){
while(true)
r.out();
}
}

public class InputOutputDemo2{
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
生产者与消费者问题:
public class ProducerConsumerDemo {
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();
}
}

/*
对于多个生产者和消费者。为什么要定义while判断标记。
原因:让被唤醒的线程再一次判断标记。

为什么定义notifyAll?
因为需要唤醒对方线程。因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。
*/
public 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){}
this.name = name+"--"+count++;

System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;
this.notifyAll();
}

public synchronized void out(){
while(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);
flag = false;
this.notifyAll();
}
}

public class Producer implements Runnable{
private Resource res;

public Producer(Resource res){
this.res = res;
}
public void run(){
while(true)
res.set("+商品+");
}
}

public class Consumer implements Runnable{
private Resource res;

public Consumer(Resource res){
this.res = res;
}
public void run(){
while(true)
res.out();
}
}
JDK1.5 中提供了多线程升级解决方案。
1)将同步Synchronized替换成现实Lock操作。
2)将Object中的wait,notify ,notifyAll,替换了Condition对象。该对象可以Lock锁 进行获取。

public class ProducerConsumerDemo2 {
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();
}
}

public class Resource{
private String name;
private int count = 1;
private boolean flag = false;

private Lock lock = new ReentrantLock();
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();
this.name = name+"--"+count++;

System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;
condition_con.signal();
}
finally{
lock.unlock();//释放锁的动作一定要执行。
}
}

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();
}
}
}

public class Producer implements Runnable{
private Resource res;
Producer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.set("+商品+");
}
catch (InterruptedException e){}
}
}
}

public class Consumer implements Runnable{
private Resource res;
public Consumer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.out();
}
catch (InterruptedException e){}
}
}
}