进程:是一个正在执行的程序
每一个进程执行都有一个顺序,该顺序是一个执行路径,或者叫一个控制单元。
线程:就是进程中的一个独立的控制单元,线程控制着进程的执行
一个进程至少有一个线程。
JVM启动时就会有一个java.exe进程
该进程中至少一个线程负责java程序的执行,而且这个线程运行的代码存在于main方法中,称为主线程。
扩展:JVM启动时不止一个线程,还负责垃圾回收机制的线程。
演示第一种创建线程的方法
1.定义类继承Thread方法
因为Thread类是线程对象描述类,继承Thread类
因此我自己写的这个类也就是线程对象了
2.重写run方法
java工程师们不知道他人要运行什么代码
规定了run方法,不管运行什么程序,代码必须写进run方法
3.建立Thread类的子类对象
4.调用start()方法,线程开启运行
start()方法是Thread类的方法,子类继承的直接使用
start()开启线程,JVM会调用线程中的run方法
注意:发现运行结果每一次都不同,因为多个线程都在获取CPU的执行权。
在某一个时刻,只有一个程序运行(多核除外)
cpu在做着速度的切换,达到看上去的效果是同时运行(争夺CPU的执行权)
多线程的一个特性:随机性
线程都有自己默认的编号 通过getName()实现
static Thread currentThread():获取当前线程对象
设置线程名称:setName或者构造方法继承Thread父类的方法super
class Demo2 extends Thread
{
Demo2(String name){
super(name);
}
public void run()
{
for(int i=0;i<60;i++)
{
System.out.println(Thread.currentThread.getName()+"----run---"+i);
}
}
}
class ThreadDemo2
{
public static void main(String[] args)
{
Demo2 d1=new Demo2("Demo1");//创建好一个线程
Demo2 d2=new Demo2("Demo2"); //d1.run仅仅是对象调用方法,线程创建了却并没有执行。
d1.start(); //开启线程,并执行该线程的run方法。
d2.start();
for(int i=0;i<60;i++)
{
System.out.println("---main---"+i);
}
}
}
创建线程的第二种方法:实现Runnable接口
* 步骤:
* 1.定义实现Runnable接口
* 2.覆盖Runnable接口中的run方法
* 将线程要运行的代码放在run方法中
* 3.通过Thread类建立线程对象
* 4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造方法
* 自定义的run方法所属的对象是Runnable接口的子类对象,要让线程去指定对象的run方法,
* 就必须明确该run方法所属的对象
* 5.调用Thread类的start方法开启线程并调用Runnable接口子类的run方法
*
* 与第一种方式的区别:
* 实现方式的区别:避免了单继承的局限性,在定义线程时,建议使用实现方式
* 继承Thread:类线程代码存放在Thread子类的run方法中
* 实现Runnable接口:线程代码存在接口的子类的run方法中
*
* 接口中的方法不能抛出异常
class Ticket implements Runnable
{
private int tick=100;
Object obj=new Object();
boolean flag=true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--code---"+tick--);
}
}
}
}else
while (true)
show();
}
public synchronized void show()
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--show---"+tick--);
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try{Thread.sleep(5);}catch (Exception e){}
t.flag=false;
t2.start();
}
}
多线程运行出现的安全问题
* 问题的原因:
* 当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,
* 还没有执行完,另一个线程参与进来,导致了共享数据的错误。
* 解决的办法:
* 对多条操作共享数据的语句,只能让一个线程都执行完,再执行过程中其他线程不可以参加运行。
* 解决方法:同步代码块
* synchronized(对象)
* {
* 需要同步的代码
* }
* 对象如锁,持有锁的线程可以在同步中执行,没有锁的线程即使获取了CPU的执行群,也进不去
*
* 同步前提:
* 1.必须要有两个或两个以上的线程。
* 2.必须是多个线程使用同一个锁
* 必须保证同步中只能有一个线程运行
*
* 好处:解决了多线程的安全问题
* 弊端:多个线程需要判断锁,较为消耗资源。
同步函数用的是哪一个锁呢?
函数需要被对象调用,那么函数都有一个所属对象的引用,就是this.
所以同步函数使用的锁是this.
通过该程序进行验证
使用两个线程来卖票
一个线程在同步代码块中,一个线程在同步函数中
都在执行卖票动作
如果同步函数被静态修饰后,使用的锁是什么?
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码对象文件即:类名.class文件该对象的类型是Class
静态的同步方法中,使用的锁是该方法所在类的字节码文件对象 类名.class
class Ticket implements Runnable
{
private int tick=100;
Object obj=new Object();
boolean flag=true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--code---"+tick--);
}
}
}
}else
while (true)
show();
}
public synchronized void show()
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--show---"+tick--);
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try{Thread.sleep(5);}catch (Exception e){}
t.flag=false;
t2.start();
}
}
/*线程间的通讯--等待与唤醒机制
wait() notifyAll() notify() 都必须使用在同步中
并且都必须持有此线程的监视器(锁对象),因为只有同步中才有锁的概念
为什么这些操作这些线程的方法都要定义在Object类中
因为这些方法在操作同步中线程时。都必须要求标识它们所操作线程只有锁
只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒
不可以对不同锁中的线程进行唤醒
也就是说,等待和唤醒必须是同一把锁。
锁是任意对象,所以可以被任意对象调用的方法定义Object类。
输入输出同步代码
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;
this.flag=true;
this.notify();
}
public synchronized void out()
{ if(!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("mike","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 InputOutputDemo2
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
/*生产者与消费者
在多名生产者与多名消费者时,必须使用while(flag)进行循环判断,这样才可以避免
生产多个产品只消费一个或者一个产品多名消费者消费
同时在使用while(flag)进行循环判断时,必须使用notifyAll()对等待池中所有等待线程进行唤醒
否则会出现所有线程全部处于等待冻结状态
*/
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();
}
}
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{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.set("+商品");
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
/* 使用lock锁替换synchronized 1.5版本后的升级版
JDK1.5中提供了多线程升级解决方案
将同步synchronized替换成现实lock操作
将Object中的wait notify notifyAll替换成了Condition对象
该对象可以通过Lock锁进行获取
*/
import java.util.concurrent.locks.*;
class ProducerConsumerDemo2
{
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();
}
}
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
//通过lock实例创建Condition可以创建多个这样的对象,从而可以
//对相对应的一个线程进行唤醒,这样操作起来就十分简单了
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();
}
}
}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
try{res.set("+商品");}catch(InterruptedException e){}
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
try{res.out();}catch(InterruptedException e){}
}
}
}