Java基础之多线程
多线程:
进程:是一个正在进行中的程序。每一个进程执行都有一个执行顺序,该顺序是一个执行路径或者叫一个控制单元。
线程:是进程中的一个独立的控制单元,线程在控制着进程的执行。一个进程中至少有一个线程。
JVM启动的时候会有一个进程java.exe ,该进程中至少有一个线程负责java程序的执行,而且这个线程运行的代码存在于main方法中,该线程称之为主线程。准确的说,JVM启动不止一个线程,还有负责垃圾回收机制的线程。有多条执行路径的程序称为多线程程序。
如何在自定义的代码中自定义一个线程呢?通过API文档的查找,java已经提供了对线程这类事物的描述,就是Thread类。
创建线程的第一种方式:继承Thread类。
步骤:
1.定义类继承Thread类。
2.复写Thread类中的run方法。目的:将自定义代码存储在run方法中,让线程运行。
3.调用线程的start方法,该方法有两个作用:启动线程和调用run方法。
需求:创建两个线程,和主线程交替运行。
class Test extends Thread //定义类继承Thread类
{
private String name;
Test(String name)
{
this.name = name;
}
public void run() //复写Thread类中的run方法,该run方法中是线程的运行代码。
{
for(int x=0; x<60; x++)
System.out.println(name+"Test run ..."+x);
}
}
class ThreadTest
{
public static void main(String[] args)
{
Test t1 = new Test("one "); //创建两个线程。
Test t2 = new Test("two ");
t1.start(); //调用线程的start方法,开启线程。
t2.start();
for(int x=0; x<60; x++) //主线程执行的代码。
System.out.println("Hello World! ..." +x);
}
}
d.start()与d.run()的区别:
d.start(); 是开启线程并执行该线程的run方法。而 d.run();仅仅是对象调用方法,线程虽然创建了却并没有运行。
发现运行结果每一次都不同。因为多个线程都获取CPU的执行权。CPU执行到谁谁就运行。明确一点:在某一个时刻只能有一个程序在运行(多核除外)。 CPU在做着快速的切换以达到看上去是同时运行的效果。我们可以形象的把多线程的运行行为看做是在互相抢夺CPU的执行权。这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长时间CPU说了算。
为什么要覆盖run方法呢?
Thread类用于描述线程,该类就定义了一个功能用于存储线程要运行的代码,该存储功能就是run方法。也就是说,Thread类中的run方法用于存储线程要运行的代码。
线程的五种状态:
1.被创建。
2.运行状态:通过start()。
3.冻结:保持不动状态,放弃了执行资格。冻结结束时先回到临时状态。有sleep(time) 和wait,当线程wait()了通过notify()唤醒。
4.消亡状态:stop() 。
5.临时或阻塞状态:具备运行资格但没有执行权。
线程都有自己默认的名称:Thread-编号,该编号从0开始。当然也可以通过Thread类中的setName方法设置名称,也可以通过getName获取名称。currentThread(): 该方法是获取当前线程对象,是Thread类中的功能,因为是静态的所以要用类名调用。Thread.currentThread()。 getName() :获取线程名称。 设置线程名称:setName() 或者通过构造函数:super(name)。局部的变量在每一个线程区域当中都有独立的一份。
创建线程的第二种方式:实现Runnable接口。
步骤:
1.定义类实现Runnable接口。
2.覆盖Runnable接口中的run方法。将线程要运行的代码存放在该run方法中。
3.通过Thread类建立线程对象。
4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。为什么要将Runnable接口的子类对象传递给Thread的构造函数呢?因为自定义的run方法所属的对象是Runnable接口的子类对象,所以想要让线程去执行指定对象的run方法就必须明确该run方法所属的对象。
5.调用Thread类的start方法开启线程并调用Runnable接口子类的run方法。
实现方式示例:需求:简单的买票程序,多个窗口同时买票,一共60张票。
class Ticket implements Runnable //实现Runnable接口
{
private int tick = 60;
public void run()
{
while(true)
{
if(tick > 0)
{
System.out.println(Thread.currentThread().getName()+"...sale:.."+tick--);
}
}
}
}
class ThreadTicket
{
public static void main(String[] args)
{
Ticket t = new Ticket(); //创建Runnable接口的子类对象。
//创建线程对象,将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.start();
t2.start(); //调用start方法开启线程。
t3.start();
}
}
实现方式好处:避免了单继承的局限性。在定义线程时建议使用实现方式。
实现方式与继承方式的区别:继承Thread,线程代码存放在Thread子类的run方法中。实现Runnable,线程代码存放在接口的子类的run方法中。
线程的安全问题:多线程的运行出现了安全问题。线程的安全问题发生的概率也许很低,但是一旦发生就是很致命的问题。
问题原因:当多条线程的语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行,导致共享数据的错误。
解决办法:让一个线程都执行完多条操作共享数据的语句,在执行过程中不让其他线程参与执行。
java对于多线程的安全问题提供了专业的解决方式,就是同步代码块。格式:synchronized(对象){ 需要被同步的代码 }
判断哪些代码需要被同步就看哪些代码在操作共享数据。对象如同锁,持有锁的线程可以在同步中执行,没有持有锁的线
程即使获取CPU的执行权也进不去,因为没有获取锁。 要保证同步中只能有一个线程在运行。
同步的前提:
1.要有两个或以上的线程,单线程不可以。
2.是多个线程使用同一个锁。
好处:解决了多线程的安全问题。弊端:多个线程需要判断锁,较为消耗资源。
同步有两种方式:
1.同步代码块,格式:synchronized(对象){ 需要被同步的代码 }。
2.同步函数:只需要将关键字synchronized作为修饰符放在函数上就可以了。也不需要创建对象了。使同步变得简单化了。
class Ticket implements Runnable
{
private int tick = 80;
Object ob = new Object();
public void run()
{
while(true)
{
synchronized(ob) //加入同步代码块使线程更安全。
{
if(tick > 0)
{
try{Thread.sleep(10);}catch(Exception e){};
System.out.println(Thread.currentThread().getName()+"...sale:.."+tick--);
}
}
}
}
}
class ThreadTicket1
{
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);
t1.start();
t2.start();
t3.start();
}
}
怎么找多线程的安全问题呢?
1.明确哪些代码是多线程的运行代码。
2.明确哪些是共享数据。
3.明确多线程运行代码中哪些语句是操作共享数据的。
需求:有两个储户往银行存钱,每次存100元,每人存3次。用一个变量sum记录他们往银行里存的钱。同步函数示例:
class Bank
{
private int sum;
public synchronized void add(int m)
{
sum = sum + m;
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("sum="+sum);
}
}
class Cus implements Runnable
{
private Bank b = new Bank();
public void run()
{
for(int x=0; x<3; x++)
{
b.add(100);
}
}
}
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 。
死锁的原理:同步中嵌套同步而锁却不同。尽量避免死锁。
懒汉式单例设计模式特点是实例的延迟加载,多线程访问时会出现安全问题,可以加同步解决,用同步代码块和同步函数都可以解决,但稍微低效。用双重判断的形式能解决低效问题。加同步使用的锁是该类所属的字节码文件对象。
多线程懒汉式单例设计模式:
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;
}
}
线程间通信:多个线程在操作同一个资源,但操作的动作不同。
等待唤醒机制:
wait(),notify(),notifyall() 这些方法都是用在同步中。因为要对持有监视器(锁)的线程操作,所以要使用在同步中。这些方法在操作同步中线程时都必须要标识它们所操作线程持有的锁,只有同一个锁上的被等待线程可以被同一个锁的notify唤醒。不可以对不同锁中的线程进行唤醒。也就是说,等待和唤醒必须是同一个锁。锁可以是任意对象,因此可以被任意对象调用的方法定义在Object类中。
wait()方法:导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。当前的线程必须拥有此对象监视器。该线程发布对此监视器的所有权并等待,直到其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来。然后该线程将等到重新获得对监视器的所有权后才能继续执行。 wait方法有异常抛出,所以要cry{}catch(){}处理,绝对不能抛。
请看下面代码:
<pre name="code" class="html"><pre name="code" class="html">class Res
{
private String name;
private String sex;
private boolean flag;
public synchronized void set(String name, String sex)
{
if(this.flag)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
this.flag = true;
this.notify();
}
public synchronized void out()
{
if(!this.flag)
try{this.wait();}catch(Exception e){}
System.out.println(this.name+"...."+this.sex);
this.flag = false;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
int x =0;
while(true)
{
if(x==0)
r.set("lisi", "man");
else
r.set("丽丽","女女");
x = (x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class InputOutputDemo1
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
多个线程操作同一个资源时,判断标记如果使用if语句会发生错乱,要用while循环判断标记,让被唤醒的线程再一次判断标记。使用while循环判断标记则会出现线程全部等待的情况处于冻结状态。这时就不能再使用notify()唤醒了,而要使用notifyAll()来唤醒。
练习: 生产者消费者示例。
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)
try{wait();}catch(Exception e){}
this.name = name+"---"+count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
flag = true;
notifyAll();
}
public synchronized void out()
{
while(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"..消费者...."+this.name);
flag = false;
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();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
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();
}
}
JDK 1.5中提供了多线程升级解决方案。将同步synchronized替换成显示的Lock操作。将Object中的wait、natify、
notifyAll替换成了Condition对象,该对象可以通过Lock锁进行获取。该示例中实现了本方只唤醒对方的操作。
condition_pro.await()等待自己 ,condition_con.signal()唤醒对方。代码演示:
import java.util.concurrent.locks.*;
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
{
while(true)
{
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
{
while(true)
{
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()
{
try
{
res.set("商品");
}
catch (InterruptedException e)
{
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
try
{
res.out();
}
catch (InterruptedException e)
{
}
}
}
class ProConTest
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
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();
}
}
停止线程:stop方法停止线程已经过时。
1.定义循环结束标记:因为线程运行代码一般都是循环,只要控制了循环即可。
2.使用interrupt(中断)方法:该方法是结束线程的冻结状态,使线程回到运行状态中来。
1.让线程停止的思想(原理):让run方法结束。开启多线程运行,运行代码通常是循环结构,只要控制住循环就可以让run方法结束,也就是线程结束。
2.当没有指定的方式让冻结的线程恢复到运行状态时就需要对冻结进行清除,强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。Thread类提供该方法:interrupt();
停止线程代码示例:
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()+"--Exception");
flag = false;
}
System.out.println(Thread.currentThread().getName()+"..run..");
}
}
public void changeFlag()
{
flag = false;
}
}
class StopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num =0;
while(true)
{
if(num++ == 60)
{
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"..."+num);
}
System.out.println("over");
}
}
守护线程(后台线程):当被标记为守护线程后,后台线程开启后和前台线程共同抢夺CPU的执行权运行,当所有前台线程都
结束后,后台线程会自动结束。setDaemon(true) 该方法必须在启动线程前调用。当前台线程全部结束,剩下的都是守护
线程时,java虚拟机退出。
join方法特点:当A线程执行到了B线程的join()方法时,A就会等待。等B线程都执行完A才会执行。
join可以用来临时加入线程执行。
什么时候用多线程呢?
当某些代码需要被同时执行时就用单独的线程进行封装。
在开发中可以不将线程单独写到一个类里,可以用匿名内部类的方式写线程。示例:
1. new Thread(){ public void run(){}}.start():这种写法是继承Thread类的方式,这是Thread类的匿名子类对象,用该对象调用start开启线程。
2. Runnable r = new Runnable(){ public void run(){}}; new Thread(r).start(); 这种写法是实现Runnable接口的方式,定义Runnable接口的子类对象:new 接口名(){ 定义子类的内容 } ,然后创建线程调用start开启线程。
代码示例:
class ThreadTest
{
public static void main(String[] args)
{
new Thread() //匿名内部类方式创建线程。————继承Thread类
{
public void run()
{
for(int x=0; x<30; x++)
{
System.out.println(Thread.currentThread().getName()+"...."+x);
}
}
}.start();
for(int x=0; x<30; x++)
{
System.out.println(Thread.currentThread().getName()+"...."+x);
}
Runnable r = new Runnable() //匿名内部类方式创建线程。————实现Runnable接口
{
public void run()
{
for(int x=0; x<30; x++)
{
System.out.println(Thread.currentThread().getName()+"...."+x);
}
}
};
new Thread(r).start();
}
}