一.多线程的概念
进程:正在运行的应用程序
线程:进程中负责程序执行的一条执行路径(控制单元)
单线程: 应用程序只有一条执行路径(控制单元)
多线程: 应用程序有多条执行路径(控制单元)
开启多线程是为了同时运行多部分代码,每一个线程都有自己运行的内容这个内容称为执行任务
多线程运行时优先让优先级高的线程使用 CPU,如果线程的优先级相同,那么会随机选择一个。(线程随机性)
因为使用多线程,就是CPU在各线程间快速切换完成的,所以会导致效率的降低。
JVM的启动至少启动了垃圾回收线程和主线程,所以是多线程。
二.多线程实现的方式
方式一:继承Thread类
自定义线程类继承Thread类。
重写run方法。run方法内为该线程执行代码
使用:创建线程对象开启线程,调用start方法,该方法会自动调用这个线程的run方法。
注:若只是单独调用run方法则只是如调用一般方法,并不会开启线程
示例:
class ThreadDemo
{
public static void main(String[] args)
{
//创建实例对象
SingleDemo s1 = new SingleDemo("张三");
SingleDemo s2 = new SingleDemo("李四");
//开启线程
s1.start();
s2.start();
//主线程
for(int i = 0;i<=100;i++)
{
System.out.println(".......i="+i+"ThreadName:"+Thread.currentThread().getName());//Thread.currentThread().getName()得到当前线程名称
}
}
}
class SingleDemo extends Thread//继承Thread类{
private String name;
public SingleDemo(String name)
{
this.name=name;
}
public void run()//重写run方法
{
//需要执行的内容
for(int i = 0;i<=100;i++)
{
//打印传进来的名字和线程名称和i值 System.out.println(name+".......i="+i+"ThreadName:"+Thread.currentThread().getName());
}
}
}
方式二:实现Runnable接口
自定义类(线程执行目标类),实现Runnable接口
覆盖接口中的run方法,将要执行的代码封装其中
通过Thread创建线程对象,再把实现Runnable接口的子类对象传入其中,调用线程的start方法开启线程,这样做避免了java单继承的局限性。
示例:
class ThreadDemo
{
public static void main(String[] args)
{
//使用匿名对象开启线程
new Thread(new MoreDemo("范冰冰")).start();
new Thread(new MoreDemo("白百合")).start();
new Thread(newMoreDemo("baby")).start();
//主线程
for(int i = 0;i<=100;i++)
{
System.out.println(".......i="+i+"ThreadName:"+Thread.currentThread().getName());//Thread.currentThread().getName()得到当前线程名称
}
}
}
class MoreDemo implements Runnable//定义类实现Runnable接口
{
private String name;
public MoreDemo(String name)
{
this.name=name;
}
public void run()//重写run方法
{
//需要执行的内容
for(int i = 0;i<=100;i++)
{
//打印传进来的名字和线程名称和i值 System.out.println(name+".......i="+i+"ThreadName:"+Thread.currentThread().getName());
}
}
}
多线程常用方法:
void start()开启线程
String getName()获取线程名称
void setName(String name)设置线程名称
static Thread currentThread()获取当前的线程
static void yield()暂停当前正在执行线程,执行其他线程
static void sleep(long millis)线程休眠,纳秒数
void interrupt()中断线程
void setPriority(int newPriority)设置线程的优先级
int getPriority()得到线程的优先级
三.线程的优先级
线程优先级代表了抢占CPU的能力。优先级越高,抢到CPU执行的可能性越大。分为1-10.
其中默认的初始优先级时5
示例:
class ThreadDemo
{
public static void main(String[] args)
{
Test t = new Test("张三");//创建对象
Test t1 = new Test("李四");//创建对象
Thread th = new Thread(t);//创建线程对象
Thread th1 = new Thread(t1);//创建线程对象
th.setPriority(10);//设置优先级为10
int i = th1.getPriority();//得到线程优先级
System.out.println(”th1线程优先级为:”+i);
th.start();//开启线程
th1.start();//开启线程
}
}
class Test implements Runnable//定义类实现Runnable接口
{
private String name;
public Test(String name)//定义有参构造函数
{
this.name=name;
}
public void run()//覆盖run方法
{
for(int i=0;i<=10;i++)
{
System.out.println(Thread.currentThread().getName()+"....i....."+i+":::name:::"+name);
}
}
}
三.线程的状态
被创建:开启线程,start()
运行状态:拥有执行权,也拥有执行资格
冻结状态:释放执行权,释放执行资格
消亡:interrupt();stop()
阻塞状态:拥有执行资格,但是没有执行权
四.线程安全问题
如模拟线程买票100张,可能会卖出负数,这显然是不可取的
那么产生安全问题的原因是什么呢?
多个线程操作同一数据,操作共享数据的代码有多条
当一个线程在操作数据时,另一个线程进来了,就会产生安全问题
那么如何解决安全问题呢?
把操作共享数据的代码封装,一个线程未完成操作,其他线程不可以进来,而该方法在java中就是同步代码块。
同步代码块格式:
Synchronize(对象)
{
//封装的代码
}
使用同步代码块以后将不会在出现上述问题
示例:
class TicketDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();//创建Runnable子类对象
//开启线程
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class Ticket implements Runnable
{
private int ticket = 100;
public void run()
{
while(true)
{
synchronized(this)//定义同步代码块
{
if(ticket>0)
{
//对同一数据进行操作
System.out.println(Thread.currentThread().getName()+"..sale..."+ticket--);
}
}
}
}
}
同步函数,在函数上加上synchronize即可:
示例:class SaleTicket
{
private int ticket=100;
public synchronized void sale()//同步函数
{
System.out.println("..sale..."+ticket--);
}
}
同步函数和同步代码块的区别:
同步函数的锁是固定的this,而同步代码块则是任意对象,
当同步代码块也使用this锁时也可以同步。
示例:
class TicketDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();//创建Runnable子类对象
//开启线程
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
//下面代码是为了防止t1还未运行标记就已经改变
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
class Ticket implements Runnable
{
private int ticket = 100;
public boolean flag =false;
public void run()
{
if(flag)
{
while(true)
{
synchronized(this)//定义同步代码块
{
if(ticket>0)
{
//让线程睡一会
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//对同一数据进行操作
System.out.println(Thread.currentThread().getName()+"..sale..."+ticket--);
}
}
}
}
else
{
while(true)
{
show();
}
}
}
public synchronized void show()//定义同步函数
{
if(ticket>0)
{
//让线程睡一会
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//对同一数据进行操作
System.out.println(Thread.currentThread().getName()+"..sale..."+ticket--);
}
}
}
当同步函数被静态所修饰时用的是什么锁呢?
因为静态函数加载是所属于类的,那时该类对象还没创建,但是该类的字节码文件已经加载进内存封装成了对象,所以静态函数的锁就是该类的字节码文件对象,该对象为 类名.class。
当同步代码块也使用字节码文件对象锁是,也可以和静态函数实现同步
多线程下的单例设计模式:
饿汉式:因为懒汉式先定义了所以存在同时多个线程操作数据的情况
示例:
class Single
{
private static final Single s = new Single();
private Single(){}
public static Single newInstance()
{
return s;
}
}
懒汉式:存在安全问题,可以用同步解决
如果直接用同步函数效率有点低,所以可以这么写:
class Single
{
private static Single s = null;
private Single(){}
public static Single newInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
s = Single();
}
}
return s;
}
}
死锁示例:
class DathLock
{
public static void main(String[] args)
{
new Thread(new TestDemo(true)).start();//开启线程传入true
new Thread(new TestDemo(false)).start();//开启线程传入false
}
}
class TestDemo implements Runnable
{
private boolean flag;
public TestDemo(boolean flag)
{
this.flag=flag;//定义标记
}
public void run()
{
if(flag)
{
while(true)
{
synchronized(MyLock.obja)//使用a锁
{
System.out.println(Thread.currentThread().getName()+"if.....obja");
synchronized(MyLock.objb)//使用b锁
{
System.out.println(Thread.currentThread().getName()+"if.....objb");
}
}
}
}
else
{
while(true)
{
synchronized(MyLock.objb)//使用b锁
{
System.out.println(Thread.currentThread().getName()+"else.....objb");
synchronized(MyLock.obja)//使用a锁
{
System.out.println(Thread.currentThread().getName()+"else.....obja");
}
}
}
}
}
}
class MyLock
{
public static final Object obja = new Object();//定义a锁
public static final Object objb = new Object(); //定义b锁
}
线程间的通讯
其实就是多个线程在操作同一数据,但是操作的动作不一致
等待唤醒机制(线程间的通信):涉及的方法:
wait:将同步中的线程处于冻结状态。释放了执行权,释放了资格。同时将线程对象存储到线程池中。
notify:唤醒线程池中某一个等待线程。
notifyAll:唤醒的是线程池中的所有线程。
上述方法必须定义在同步中,因为是用来操作线程状态的方法
wait和sleep的区别:
wait不需要定义时间,而sleep需要,
wait:释放执行权,释放锁
sleep:释放执行权,不释放锁
多生产者多消费者示例:
同一个锁上的线程被等待,只有被同一个锁上notify唤醒。不可以对不同锁中的线程进行唤醒。也就是说,等待和唤醒必须是同一个锁。
但是可以使用notifyAll()唤醒的是线程池中的所有线程
class ProComDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Consumer c = new Consumer(r);
Producer p = new Producer(r);
new Thread(c).start();
new Thread(c).start();
new Thread(p).start();
new Thread(p).start();
}
}
class Resource
{
private String name ;
private int num ;
public boolean flag = false;
public synchronized void set(String name)
{
while(flag)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.name=name+(++num);
System.out.println(Thread.currentThread().getName()+"生产者......"+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"消费者......"+this.name);
flag = false;
this.notifyAll();
}
}
class Consumer implements Runnable
{
private Resource r;
public Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class Producer implements Runnable
{
private Resource r;
public Producer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("龙虾");
}
}
}
JDK1.5后多线程升级解决方案。将同步Synchronized替换成接口Lock。
将Object中的wait,notify notifyAll,替换了Condition对象。
Lock:替代了Synchronized
lock():获取锁
unlock():释放锁
Condition:替代了wait() notify() notifyAll()
await(); signal(); signalAll();
示例:
import java.util.concurrent.locks.*;
class ProComDemo
{
public static void main(String[] args)
{
Resource r = new Resource();//定义资源
Consumer c = new Consumer(r);//消费者
Producer p = new Producer(r);//生产者
//开启线程
new Thread(c).start();
new Thread(c).start();
new Thread(p).start();
new Thread(p).start();
}
}
class Resource
{
private String name ;
private int num ;
public boolean flag = false;
//创建一个锁对象
private Lock lock = new ReentrantLock();
//创建监视器对象
private Condition con_pro = lock.newCondition();
private Condition con_con = lock.newCondition();
public void set(String name)
{
lock.lock();
try
{
while(flag)
{
try
{
con_pro.await();//生产者等待
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.name=name+(++num);
System.out.println(Thread.currentThread().getName()+"生产者......"+this.name);
flag = true;
con_con.signal();//唤醒消费者
}
finally
{
lock.unlock();//释放锁的动作一定要执行。
}
}
public synchronized void out()
{
lock.lock();
try
{
while(!flag)
{
try
{
con_con.await();//消费者等待
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"消费者......"+this.name);
flag = false;
con_pro.signal();//唤醒生产者
}
finally
{
lock.unlock();//释放锁的动作一定要执行。
}
}
}
class Consumer implements Runnable
{
private Resource r;
public Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class Producer implements Runnable
{
private Resource r;
public Producer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("鱿鱼");
}
}
}
线程的其他方法:
守护线程:也可以理解为后台线程,之前创建的都是前台线程。
只要线程调用了setDaemon(true);就可以把线程标记为守护线程。前台线程要通过run方法结束,线程结束。后台线程跟前台线程一样,但是当前台线程都结束时,无论守护线程在做什么操作,都会结束
加入线程:public final void join():等待该线程终止。 当A线程执行到了B 线程的join()方法时,A就会等待。等B线程都执行完,A才会执行。
暂停线程:public static void yield():暂停当前正在执行的线程对象,并执行其他线程。
线程中断:stop方法已过时,通常使用interrupt方法。