关闭

JAVA基础-多线程

标签: java多线程
215人阅读 评论(0) 收藏 举报
分类:


1、概述

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

线程:就是进程中的一个独立的控制单元,线程在控制着进程的执行。一个进程中至少有一个线程。

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

2、创建线程

2.1、继承Thread类

(1)步骤:

-定义类并继承Thread。

-复写Thread类中的run方法。目的是将自定义代码存储在run方法中让线程运行。

-调用线程的start方法,该方法有两个作用,即启动线程和调用run方法。

示例:

//定义Demo类继承Thread

class Demo extends Thread

{

         //复写从thread类继承的run方法

         publicvoid run()

         {

                   for(inti=0;i<600;i++)

                            System.out.println("Demorun--"+i);

         }

}

public class ThreadDemo

{

         publicstatic void main(String[] args)

         {

                   //创建线程

                   Demod=new Demo();

                   //开启线程

                   d.start();

                   for(inti=0;i<600;i++)

                   {

                            System.out.println("mainrun----"+i);

                   }

         }

}


运行结果:


说明:上述程序中创建了一个线程后,程序中就有两个线程在同时执行。

因为多个线程都在获取CPU的执行权,CPU执行到谁,谁就运行,而在某一个时刻,只能有一个程序在运行(多核除外),CPU在做着快速的切换,以达到看上去是同时运行的效果,我们可以把多线程运行行为是在互相抢夺CPU的执行权,这是多线程的一个特性,即随机性,谁抢到谁执行。

(2)run方法:Thread类用于描述线程,该类定义了一个功能,用于存储线程要运行的代码,该存储功能就是run方法。也就是 Thread类中的run方法用于存储线程要运行的代码。

(3)start方法:用于开启线程并执行该线程的run方法。

(4)线程运行状态:


(5)获取线程名称:线程都有自已默认的名称,即Thread-编号,该编号从0开始。获取线程名称可用Thread类的getName()方法。

(6)设置线程名称:可以用Thread类的setName(Stringname)方法改变线程名称,也可以在创建线程时通过构造方法设置线程的名称。

(7)currentThread()方法:返回对当前正在执行的线程对象的引用。该方法是静态方法,返回值类型是Thread。

2.2、实现Runable接口

(1)步骤:

-定义类实现Runable接口。

-覆盖Runable接口中的run方法。将线程要运行的代码存放在run方法中

-通过Thread类建立线程对象。

-将Runable接口的子类对象作为实际参数传递给Thread类的构造函数创建Thread类的对象。因为自定义的run方法所属的对象是Runable接口的子类对象,所以要让线程去调用指定对象的run方法,就必须明确该run方法所属的对象。

-调用Thread类的start方法开启线程并调用Runable接口子类的run方法。

示例:

//定义Ticket类实现Runnable接口

class Ticket implements Runnable

{

         privateint tick=100;

         //复写Runnable接口的run方法

         publicvoid run()

         {

                   while(true)

                   {

                            if(tick>0)

                            {

                                     System.out.println(Thread.currentThread().getName()+"..."+tick--);

                            }

                   }

         }

}

public class TicketDemo

{

         publicstatic void main(String[] args)

         {

                   Tickett=new Ticket();

                   //创建线程

                   Threadt1=new Thread(t);

                   Threadt2=new Thread(t);

                   Threadt3=new Thread(t);

                   //开启线程

                   t1.start();

                   t2.start();

                   t3.start();

         }

}


运行结果:

说明:上述程序通过实现Runnable接口的类创建线程,实现简单的卖票程序。

(2)实现Runnable方式与继承Thread方式的区别:

-实现Runable:线程代码存在Runable接口的子类的run方法中。

-继承Thread:线程代存放在Thread子类run方法中。

(3)实现Runnable接口的好处:避免了单继承的局限性,在定义线程时,建议使用实现方式。

3、多线程的安全问题

(1)原因:当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行,导致共享数据的错误。在前面卖票程序中,若某一个线程执行完if语句但执行输出语句之前进入了冻结状态,此时又有另一个线程进来,那么就可能出现tick是负数的情况。


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

(3)JAVA对于多线程的安全问题提供了解决方式:即同步代码块。

格式:

class Ticket implements Runnable

{

         privateint ticket=100;

         privateObject obj=new Object();

         //复写run方法

         publicvoid run()

         {

                   while(true)

                   {

                            //定义同步代码块

                            synchronized(obj)

                            {

                                     if(tick>0)

                                     {

                                               try

                                               {

                                                        //线程进入睡眠状态

                                                        Thread.sleep(10);

                                               }

                                               catch(InterruptedExceptione)

                                               {

                                                        System.out.println(e.toString());

                                               }

                                               System.out.println(Thread.currentThread.getName()+"..."+ticket--);

                                     }

                            }

                   }

         }

}


(4)同步的前提:

-必须要有两个或者两个以上的线程。

-必须是多个线程使用同一个锁。

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

好处:解决了多线程的安全问题。

弊端:多个线程需要判断锁,较为消耗资源。

4、同步函数

(1)同步函数在声明时用synchronized关键字修饰。

如声明一个同步函数:publicsynchronized void show(){}

(2)同步函数用的锁是this,因为函数需要被对象调用,而函数都有一个所属对象引用,即this。

验证:

//定义Ticket类实现Runnable接口

class Ticket implements Runnable

{

         privateint tick=100;

         privateObject obj=new Object();

         booleanflag=true;

         //复写Runnable接口的run方法

         publicvoid run()

         {

                   //flaytrue执行的代码

                   if(flag)

                   {

                            while(true)

                            {

                                     synchronized(this)

                                     {

                                               if(tick>0)

                                               {

                                                        try

                                                        {

                                                                 //线程进行睡眠状态

                                                                 Thread.sleep(10);

                                                        }

                                                        catch(InterruptedExceptione)

                                                        {

                                                                 System.out.println(e.toString());

                                                        }

                                                        System.out.println(Thread.currentThread().getName()+"..."+tick--);

                                               }

                                     }

                            }

                   }

                   //flagfalse时执行的代码

                   else

                            while(true)

                                     show();

         }

         publicsynchronized void show()

         {

                   if(tick>0)

                   {

                            try

                            {

                                     Thread.sleep(10);

                            }

                            catch(InterruptedExceptione)

                            {

                                     System.out.println(e.toString());

                            }

                            System.out.println(Thread.currentThread().getName()+"....."+tick--);

                   }

         }

}

public class TicketDemo

{

         publicstatic void main(String[] args)

         {

                   //创建线程

                   Tickett=new Ticket();

                   Threadt1=new Thread(t);

                   Threadt2=new Thread(t);

                   //开启线程t1

                   t1.start();

                   try

                   {

                            Thread.sleep(10);

                   }

                   catch(Exceptione)

                   {

                            System.out.println(e.toString());

                   }

                   //修改flag的值

                   t.flag=false;

                   //开启线程t2

                   t2.start();

         }

}


运行结果:


说明:上述程序中,让两种线程中其中一个执行同步代码块,一个执行同步函数,将同步代码块中的锁设为this,从运行结果看出程序实现了同步,所以在该程序中,同步函数和同步代码块使用了同一个锁,即this。

(3)静态同步函数使用的锁是该方法所在类的字节码文件对象,因为静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。即类名.class,该对象的类型是Class。

5、死锁

通常在同步中嵌套同步的时候会发生死锁。

示例:

class Test implements Runnable

{

         privateboolean flag;

         publicTest(boolean flag)

         {

                   this.flag=flag;

         }

         publicvoid run()

         {

                   if(flag)

                   {

                            while(true)

                            {

                                     //在同步代码块内嵌套一个同步代码块并使用不同的锁

                                     synchronized(MyLock.locka)

                                     {

                                               System.out.println("if..locka");

                                               synchronized(MyLock.lockb)

                                               {

                                                        System.out.println("if..lockb");

                                               }

                                     }

                            }

                   }

                   else

                   {

                            while(true)

                            {

                                     //在同步代码块内嵌套一个同步代码块并使用不同的锁

                                     synchronized(MyLock.lockb)

                                     {

                                               System.out.println("else...lockb");

                                               synchronized(MyLock.locka)

                                               {

                                                        System.out.println("else...locka");

                                               }

                                     }

                            }

                   }

         }

}

//定义锁

class MyLock

{

         staticObject locka=new Object();

         staticObject lockb=new Object();

}

public class DeadLock

{

         publicstatic void main(String[] args)

         {

                   //创建线程

                   Threadt1=new Thread(new Test(true));

                   Threadt2=new Thread(new Test(false));

                   //开启线程

                   t1.start();

                   t2.start();

         }

}


运行结果:

6、线程间的通信

(1)概念:线程间的通信其实就是多个线程在操作同一个资源,但是操作的动作不同。

示例:

//定义资源

class Res

{

         Stringname;

         Stringsex;

}

//定义生产者

class Input implements Runnable

{

         privateRes r;

         publicInput(Res r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   intx=0;

                   //生产资源

                   while(true)

                   {

                            synchronized(r)

                            {

                                     if(x==0)

                                     {

                                               r.name="mike";

                                               r.sex="man";

                                     }

                                     else

                                     {

                                               r.name="lily";

                                               r.sex="woman";

                                     }

                                     x=(x+1)%2;

                            }

                   }

         }

}

//定义消费者

class Output implements Runnable

{

         privateRes r;

         publicOutput(Res r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   //消费资源

                   while(true)

                   {

                            synchronized(r)

                            {

                                     System.out.println(r.name+"..."+r.sex);

                            }

                   }

         }

}

public class InputOutput

{

         publicstatic void main(String[] args)

         {

                   Resr=new Res();

                   //创建生产者线程

                   Threadt1=new Thread(new Input(r));

                   //创建消费者线程

                   Threadt2=new Thread(new Output(r));

                   //开启线程

                   t1.start();

                   t2.start();

         }

}



(2)等待唤醒机制

从上面示例的运行结果中,出现了输入线程输入一次,而输出线程输出了多次,而实际情况是要求输入一次,输出一次。此时需要通过等待唤醒机制来实现,以下为修改后的代码:

//定义资源

class Res

{

         Stringname;

         Stringsex;

}

//定义生产者

class Input implements Runnable

{

         privateRes r;

         publicInput(Res r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   intx=0;

                   //生产资源

                   while(true)

                   {

                            synchronized(r)

                            {

                                     if(x==0)

                                     {

                                               r.name="mike";

                                               r.sex="man";

                                     }

                                     else

                                     {

                                               r.name="lily";

                                               r.sex="woman";

                                     }

                                     x=(x+1)%2;

                            }

                   }

         }

}

//定义消费者

class Output implements Runnable

{

         privateRes r;

         publicOutput(Res r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   //消费资源

                   while(true)

                   {

                            synchronized(r)

                            {

                                     System.out.println(r.name+"..."+r.sex);

                            }

                   }

         }

}

public class InputOutput

{

         publicstatic void main(String[] args)

         {

                   Resr=new Res();

                   //创建生产者线程

                   Threadt1=new Thread(new Input(r));

                   //创建消费者线程

                   Threadt2=new Thread(new Output(r));

                   //开启线程

                   t1.start();

                   t2.start();

         }

}

 

 

 

//定义资源

class Res

{

         Stringname;

         Stringsex;

         booleanflag=false;

}

//定义生产者

class Input implements Runnable

{

         privateRes r;

         publicInput(Res r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   intx=0;

                   while(true)

                   {

                            synchronized(r)

                            {

                                     //如果flagture则进行等待

                                     if(r.flag)

                                     {

                                               try

                                               {

                                                        r.wait();

                                               }

                                               catch(Exceptione)

                                               {

                                                        System.out.println(e.toString());

                                               }

                                     }

                                     //生产资源     

                                     if(x==0)

                                     {

                                               r.name="mike";

                                               r.sex="man";

                                     }

                                     else

                                     {

                                               r.name="lily";

                                               r.sex="woman";

                                     }

                                     x=(x+1)%2;

                                     //flag设置为true

                                     r.flag=true;

                                     //唤醒对方线程

                                     try

                                     {

                                               r.notify();

                                     }

                                     catch(Exceptione)

                                     {

                                               System.out.println(e.toString());

                                     }

                            }

                   }

         }

}

//定义消费者

class Output implements Runnable

{

         privateRes r;

         publicOutput(Res r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   while(true)

                   {

                            synchronized(r)

                            {

                                     //如果flagfalse则进行等待

                                     if(!r.flag)

                                     {

                                               try

                                               {

                                                        r.wait();

                                               }

                                               catch(Exceptione)

                                               {

                                                        System.out.println(e.toString());

                                               }

                                     }

                                     //消费资源

                                     System.out.println(r.name+"..."+r.sex);

                                     //设置flagfalse

                                     r.flag=false;

                                     //唤醒对方线程

                                     try

                                     {

                                               r.notify();

                                     }

                                     catch(Exceptione)

                                     {

                                               System.out.println(e.toString());

                                     }

                            }

                   }

         }

}

public class InputOutput2

{

         publicstatic void main(String[] args)

         {

                   Resr=new Res();

                   //创建生产者线程

                   Threadt1=new Thread(new Input(r));

                   //创建消费者线程

                   Threadt2=new Thread(new Output(r));

                   //开启线程

                   t1.start();

                   t2.start();

         }

}


运行结果:


说明:代码修改后,实现了输入一次输出一次的要求。

注意:wait(),notify(),notifyAll()方法都使用在同步中,因为要对持有监视器(锁)的线程操作,所以要使用在同步中,国为只有同步才具有锁。因为这些方法在操作同步中线程时,都必须要标识它们所操作线程持有的锁,只有同一个锁上的被等待线程,可以被同一个锁上notify()唤醒,不可以对不同锁中的线程进行唤醒。即等待和唤醒必须是同一个锁。而锁可以是任意对象,所以可以被任意对象调用的方法定义Object类中。

public class ProCon

{

         publicstatic void main(String[] args)

         {

                   //创建资源

                   Resourser=new Resourse();

                   //创建生产者

                   Producerpro=new Producer(r);

                   //创建消费者

                   Consumercon=new Consumer(r);

                   //创建生产者线程

                   Threadt1=new Thread(pro);

                   Threadt2=new Thread(pro);

                   //创建消费者线程

                   Threadt3=new Thread(con);

                   Threadt4=new Thread(con);

                   //开启线程

                   t1.start();

                   t2.start();

                   t3.start();

                   t4.start();

         }

}

//定义资源

class Resourse

{

         privateString name;

         privateint count=1;

         //定义标记

         privateboolean flag=false;

         //定义生产资源方法

         publicsynchronized void set(String name)

         {

                   //使用while循环使线程每次醒来所都判断flag

                   while(flag)

                   {

                            try

                            {

                                     //线程进入等待

                                      wait();

                            }

                            catch(Exceptione)

                            {

                                     System.out.println(e.toString());

                            }

                   }

                   this.name=name+"--"+count++;

                   System.out.println(Thread.currentThread().getName()+"..producer.."+this.name);

                   //生产资源后将flag设置为true

                   flag=true;

                   //唤醒对方线程

                   notifyAll();

         }

         //定义消费资源的方法

         publicsynchronized void out()

         {

                   //使用while循环使线程每次醒来所都判断flag

                   while(!flag)

                   {

                            try

                            {

                                     //线程进入等待

                                     wait();

                            }

                            catch(Exceptione)

                            {

                                     System.out.println(e.toString());

                            }

                   }

                   System.out.println(Thread.currentThread().getName()+"..consumer....."+this.name);

                   //消费资源后将flag设置为true

                   flag=false;

                   //唤醒对方线程

                   notifyAll();

         }

}

//定义生产者

class Producer implements Runnable

{

         privateResourse r;

         publicProducer(Resourse r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   while(true)

                   {

                            r.set("+thing+");

                   }

         }

}

//定义消费者

class Consumer implements Runnable

{

         privateResourse r;

         publicConsumer(Resourse r)

         {

                   this.r=r;

         }

         //复写run方法

         publicvoid run()

         {

                   while(true)

                   {

                            r.out();

                   }

         }

}


运行结果:

说明:在多生产者和多消费者的情况,通过使用while循环让被唤醒的线程再一次判断标记,使用notifyAll唤醒所有等待的线程,若只用notify容易出现只唤醒本方线程的情况,导致程序中的所有线程都等待。

(4)Lock接口和Condition接口

Lock和Confition是JDK1.5中提供的多线程解决方案,将同步synchronized替换成了显式Lock操作,Lock中通过lock()方法获取锁,通过unlock()方法释放锁,通过newCondition()方法获取Condition对象,Condition对象用await()、signal()和signalAll()方法替换了Object中的wait()、notify()和notifyAll()方法。

可以对生产者消费者的程序做以下修改:

import java.util.concurrent.locks.*;

public class ProCon2

{

         publicstatic void main(String[] args)

         {

                   Resourser=new Resourse();

                   Producerpro=new Producer(r);

                   Consumercon=new Consumer(r);

                   Threadt1=new Thread(pro);

                   Threadt2=new Thread(pro);

                   Threadt3=new Thread(con);

                   Threadt4=new Thread(con);

                   t1.start();

                   t2.start();

                   t3.start();

                   t4.start();

         }

}

class Resourse

{

         privateString name;

         privateint count=1;

         privateboolean flag=false;

         privateLock lock=new ReentrantLock();

         privateCondition condition_pro=lock.newCondition();

         privateCondition condition_con=lock.newCondition();

         //定义生产资源方法

         publicvoid set(String name)throws Exception

         {

                   //获取锁

                   lock.lock();

                   try

                   {

                            while(flag)

                                     //线程进入等待

                                     condition_pro.await();

                            this.name=name+"--"+count++;

                            System.out.println(Thread.currentThread().getName()+"..producer.."+this.name);

                            flag=true;

                            //唤醒对方线程

                            condition_con.signal();

                   }

                   finally

                   {

                            //释放锁

                            lock.unlock();

                   }

         }

         //定义消费资源方法

         publicvoid out()throws Exception

         {

                   //获取锁

                   lock.lock();

                   try

                   {

                            while(!flag)

                                     //线程进入等待

                                     condition_con.await();

                            System.out.println(Thread.currentThread().getName()+"..consumer....."+this.name);

                            flag=false;

                            //唤醒对方线程

                            condition_pro.signal();

                   }

                   finally

                   {

                            //释放锁

                            lock.unlock();

                   }

         }

}

//定义生产者

class Producer implements Runnable

{

         privateResourse r;

         publicProducer(Resourse r)

         {

                   this.r=r;

         }

         publicvoid run()

         {

                   while(true)

                   {

                            try

                            {

                                     r.set("+thing+");

                            }

                            catch(Exceptione)

                            {

                                     System.out.println(e.toString());

                            }

                   }

         }

}

//定义消费者

class Consumer implements Runnable

{

         privateResourse r;

         publicConsumer(Resourse r)

         {

                   this.r=r;

         }

         publicvoid run()

         {

                   while(true)

                  {

                            try

                            {

                                     r.out();

                            }

                            catch(Exceptione)

                            {

                                     System.out.println(e.toString());

                            }

                   }

         }

}


说明:通过两个Condition对象实现了本方只唤醒对方线程的操作。一个锁可以对应多个Conditon对象。

7、停止线程

(1)如何停止线程:因为Thread中的stop方法已过时,所以只有一种方式停止线程,即run方法结束。而开启多线程运行,运行代码通常都是循环结构的,只要控制循环,就可以让run方法结束,即线程结束。

特殊情况:当线程处于了冻结状态(中断状态),就不会读取到标记,那么线程就不会结束。当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除(用interrupted方法),强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。

(2)interrupted()方法:如果线程在调用 Object类的wait方法,或者该类的 join方法sleep方法过程中受阻,则其中断状态将被清除,它还将收到一个InerruptedException。

8、Thread中常用方法

(1)setDaemon(boolean on)方法:将线程标记为守护线程或用户线程(后台线程),当正在运行的线程都是守护线程时,JAVA虚拟机退出,该方法必须在启动线程前调用。如果该方法的参数为true,则将该线程标记为守护线程。

(2)join方法:当A线程执行到了B线程的join()方法时,A就会等待,等B线程都执行完,A才会执行。join方法可以用来临时加入线程执行。

(3)toString方法:返回该线程的字符串表示形式,包括线程名称、优先级和线程组。

(4)setPriority(int newPriority)方法:更改线程的优先级。优先级的取值范围从1到10。

(5)yield方法:暂停当前正在执行的线程对象,并执行其他线程。此方法是静态的。


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2112次
    • 积分:125
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档