黑马程序员----多线程

------- android培训java培训、期待与您交流! ----------

1、多线程

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

一个进程中至少有一个线程。

java 虚拟机 JVM 启动的时候会有一个进程java.exe
该进程中至少有一个线程,在负责java程序的执行。
而且这个线程运行的代码存在于main方法中。
该线程称之为主线程。

更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程。

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

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

也就是说,Thread类中的run方法,用于存储线程要运行的代码。

线程都有自己的默认名称
Thread-编号  getName();
currentThread():获取当前线程对象。
Thread.currentThread().getName();

设置线程名称:setName()或者构造函数。

class newThread extends Thread
{
public void run()
{
for(int x=0;x<60;x++)
System.out.println("newThread---"+x);
}
}
class ThreadDemo
{
public static void main(String[] args)
{
newThread nt=new newThread();//创建一个线程。
nt.start();//开启线程并执行该线程的run方法
nt.run();//仅仅是对象调用方法,而线程创建了,没有执行。
for(int x=0;x<60;x++)
System.out.println("mainThread---"+x);
}
}
//发现运行结果每一次都不同,因为多个线程都在获取cpu的执行权,cpu执行到谁,谁就运行。(对应下面的代码。)
//明确一点,在某一个时刻,只能有一个程序在运行(多核除外)
//cpu在做着快速的切换,已达到看上去是同同时运行的效果。
//我们可以形象的把多线程的运行行为在互相抢夺cpu的执行权。

//谁抢到谁执行,至于执行多长时间,cpu说了算。

创建线程方法2 :实现Runnable 接口。

1)定义类实现Runnable 接口
2)覆盖Runnable接口中的run方法
3)通过Thread简历线程对象。
4)将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。
为什么要将Runnable接口的子类对象传递给Thread的构造函数。
因为自定义的run方法所属的对象是Runnable接口的子类对象。
所以要让线程去执行指定对象的run方法。就必须明确该run方法所属的对象。
5)调用Thread类的start方法开启线程并调Runnable接口子类的run方法。

实现方式和继承方式区别:
实现方式好处:避免了单继承的局限性。
在定义线程时,建议使用实现方式。

继承Thread类:线程代码存放在Thread子类的run方法中。
实现Runnable:线程代码存放在接口子类的run方法中。

class Ticket implements Runnable
{
private int tick =100;
public void run()
{
while(true)
{
if(tick>0)
{
System.out.println(Thread.currentThread().getName()+"sale: "+tick--);


}
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}


3、线程安全问题
通过分析,发现,打印出现了0,-1,-2等错票。
多线程的运行出现了安全问题。

问题的原因:
当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行
导致了共享数据的错误。

解决办法:
对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行。

java对于多线程的安全问题提供了专业的解决方式。
就是同步代码块 
synchronized(对象){
需要被同步的语句。
}

对象如同锁,持有所得线程可以在同步中执行。
没有持有锁的线程即使获取cpu的执行权,也进不去,因为没有获取锁。

同步的前提:
1)必须要有两个或者两个以上的线程。
2)必须是多个线程使用同一个锁。

必须保证同步中只有一个线程在运行。

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

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


public class  ThreadSafeProblem
{
public static void main(String[] args) 
{
Ticket t = new Ticket();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}

同步函数:
同步函数需要被对象调用,那么函数都有一个所属对象引用。那就是 this。
所以同步函数使用的锁是this

class Bank
{
private int sum;
public synchronized void add(int num)
{
sum=sum+num;
System.out.println("sum= "+sum);
}
}


class Cus implements Runnable
{
Bank b = new Bank();
public void run()
{
for(int x = 0 ;x < 3; x ++)
{
b.add(100);
}
}
}
public BankDemo
{
public static void main(String[] args)
{
new Thread(new Cus()).start();
new Thread(new Cus()).start();
}
}


如果同步函数被静态所修饰,使用的锁是什么呢?

通过验证,发现不是this,因为静态方法中不可以定义this。

静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class  该对象的类型是Class

静态的同步方法,是用的锁是该方法所在类的字节码文件对象。

//class Single 
//{
// private Single(){};
// private static Single s = null;
// public static synchronized Single getInstance()
// {
//
// if(s==null)
// s= new Single();
// return s;
// }
//}
class Single 
{
private Single(){};
private static Single s = null;
public static  Single getInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
s= new Single();
}
}
return s;
}
}

死锁:
通常是同步嵌套同步,而锁却不同。

class Test implements Runnable
{
private boolean flga;
Test(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{
synchronized(MyLock.locka)//a锁里面有b锁
{
System.out.println("if locka");
synchronized(MyLock.lockb)
{
System.out.println("if lockb");
}
}
}
else
{
synchronized(MyLock.lockb)//b锁里面有a锁
{
System.out.println("else lockb");
synchronized(MyLock.locka)
{
System.out.println("else locka");
}
}
}
}
}
class MyLock 
{
static Object a = new Object();
static Object b = new Object();
}
class DeadLockTest
{
public static void main(String[] args)
{
new Thread(new Test(true)).start();
new Thread(new Test(false)).start();
}
}

4、线程间通信
其实就是多个线程操作同一个资源
但是操作的动作不同。

class Res
{
String name;
String sex;
}
clss Input implements Runnable
{
Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=1;
while(true)
{
if(x==1)
{
r.name="Mike";
r.sex=="nan";
}
else
{
r.name=="丽丽";
r.sex=="女";
}
x=x*(-1);
}


}
}
class Output
{
Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
System.out.println(r.name+"..."+r.sex);
}
}
}


public class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
解决方法,加同步
class Res
{
String name;
String sex;
boolean flag =false;
}
class Input implements Runnable
{
Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=1;
while(true)
{
synchronized(r)
{
if(r.flag==true)
try
{
r.wait();
}
catch (Exception e)
{
}
if(x==1)
{
r.name="Mike";
r.sex="nan";
}
else
{
r.name="丽丽";
r.sex="女";
}
x=x*(-1);
r.flag=true;
r.notify();
}
}
}
}
class Output implements Runnable
{
Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
synchronized(r)
{
if(r.flag==false)
try
{
r.wait();
}
catch (Exception e)
{
}
System.out.println(r.name+"..."+r.sex);
r.flag = false;
r.notify();
}
}
}
}


public class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}


wait()
notify()
notifyAll()
都使用在同步中,因为要对持有监视器(锁)的线程操作。
之所以要使用在同步中,因为只有同步才具有锁。

为什么这些操作线程的方法定义在Obje类中呢?
因为这些方法在操作同步中线程时,都比粗要标识他们所操作线程所持有的锁,
只有同一个锁上的被等待线程可以被同一个锁上的notify唤醒。
不可以被不同所中的线程进行唤醒。
也就是说等待和唤醒必须是同一个锁。
而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object中。

代码优化

class Res
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void setInfo(String name,String sex)
{
if(flag==true)
try
{
this.wait();
}
catch (Exception e)
{
}
this.name=name;
this.sex=sex;
flag=true;
this.notify();

}
public synchronized void getInfo()
{
if(flag==false)
try
{
this.wait();
}
catch (Exception e)
{
}
System.out.println(this.name+"..."+this.sex);
flag = false;
this.notify();
}
}
class Input implements Runnable
{
Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=1;
while(true)
{
if(x==1)
{
r.setInfo("Mike","nan");
}
else 
{
r.setInfo("丽丽","女");
}
x=x*(-1);
}
}
}
class Output implements Runnable
{
Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
r.getInfo();
}
}
}
public class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}


生产者消费者

class Resource
{
private String name;
private int count=1;
private boolean flag =false;
public synchronized void setInfo(String name)
{
while(this.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 getInfo()
{
while(!this.flag)//循环判断标记。
try
{
this.wait();
}
catch (Exception e)
{
}
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.setInfo("产品1");
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
res.getInfo();
}
}


class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource res =new Resource();
new Thread(new Producer(res)).start();
new Thread(new Consumer(res)).start();
new Thread(new Producer(res)).start();
new Thread(new Consumer(res)).start();
}
}

5、jdk 1.5 升级版本新特性
提供的升级解决方案
将同步synchronized替换成了现实Lock操作
将wait ,notify notifyAll替换成了condition对象
该对象可以通过Lock锁进行获取。
在该实例中实现了本方只唤醒对方的操作。

import java.util.concurrent.locks.*;
class Resource
{
final Lock lock=new ReentrantLock();
final Condition condition1=lock.newCondition();
final Condition condition2=lock.newCondition();
private String name;
private String num=0;
private boolean flag=false;
public void set(String name)throws InterruptedException
{
lock.lock();
while(this.flag)
try
{
condition1.await();
this.name=name;
System.out.println(Thread.currentThread().getName()+"....."+this.name+"....."+this.num);
this.flag=true;
condition2.signal();
}
finally
{
lock.unlock();
}
}
public void get()throws InterruptedException
{
lock.lock();
while(!this.flag)
try
{
condition2.await();
System.out.println(Thread.currentThread().getName()+"....."+"消费者"+"....."+this.num);
this.flag=false;
condition1.signal();
}
finally
{
lcok.unlock();
}
}
}


class Producer implements Runnable
{
Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
try
{
res.set("生产者");
}
catch (InterruptedException e)
{
}
}
}
class Consumer implements Runnable
{
Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
try
{
res.get();
}
catch (InterruptedException e)
{


}
}
}
class ProducerConsumer 
{
public static void main(String[] args) 
{
Resource r=new Resource();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
}
}


6、停止线程
stop方法已经过时,如何停止线程
只有一种:run方法结束。
开启多线程运行,运行代码通常是循环结构。
只要控制住循环,就可以让run方法结束,也就是线程结束。
特殊情况:
当线程处于冻结状态,就不会读到标记,那么线程不会结束。

当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除。
强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。
Thread中提供了该方法,interrupt();


setDaemon() 将线程设置成守护线程
join() 等待该项成终止。
当A线程执行到了B线程的join方法时,A线程就会等待,等B线程都执行完 A才会执行。
join可以用来临时加入线程执行。


class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while (flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"...excepetion");
flag =false;
}
System.out.println(Thread.currentThread().getName()+"...run");
}
}
public void changeFlag()
{
this.flag=false;
}
}


public class StopThreadDemo
{
public static void main(String[] args)throws Exception
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
//t1.setPriority(Thread.MAX_PRIORITY);//设置优先级。
//t1.join();//t1申请执行权,主线程放弃执行权,等待t1结束后继续执行。
t2.start();
int num =0;
while(true)
{
if(num++ ==60)
{
//st.changeFlag();
// t1.interrupt();
// t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"...run");
}
}
}s

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值