——- android培训、java培训、期待与您交流! ———-
一:进程与线程的概念
进程:进程是一个正在执行中的程序。每一个进程执行都有一个执行顺序,该顺序是一个执行路径,或者叫一个控制单元
线程:线程就是进程中一个独立的控制单元,线程再控制着进程的执行。
一个进程中至少有一个线程。
JVM启动时启动了多条线程,至少有两个线程:
1.执行main函数的线程,该线程的任务代码都定义在main函数中。
2.负责垃圾回收的线程。
二.线程的创建
如何在自定义的代码中,自定义一个线程呢?
通过对api的查找,java已经提供了对这类事物的描述,就是Thread类。
1.创建线程的第一种方式:继承Thread类。
步骤:
1,定义类继承Thread.
2,复写Thread类中Run方法。
目的:将自定义代码存储在run方法中,让线程运行。
3.调用线程中start(此方法有两个作用:执行线程并调用Run方法)
package Thread;
class Demo extends Thread
{
public void run()
{
for(int x =0; x<800; x++)
System.out.println("demo");
}
}
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo d=new Demo();
d.start();
for(int x=0; x<800;x++)
{
System.out.println("hello Thread"+x);
}
}
}
结果:
发现:运行结果每一次都不同。因为多个线程都获取cpu的执行权,cpu执行到谁,谁就运行。
明确一点:在某个时刻,只能有一个程序在运行。(多核除外)cpu在做着快速的切换,以达到看上去是同时运行的效果。我们可以形象地把多线程的运行行为比喻为互相抢夺cpu的执行权。
这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,由cpu决定。
为什么要覆盖run方法呢?
Thread类用于描述线程,该类就定义了一个动能,用于存储线程要运行的代码,该存储功能就是Run方法。也 就是是说Thread类中run方法用于存储线程要运行的代码。
/*
* 练习:创建两个线程,和柱线程交互运行
*/
package Thread;
class Test extends Thread
{
public void run()
{
for(int x=0; x<500; x++)
System.out.println("test run"+x);
}
}
public class ThreadTest {
public static void main(String[] args) {
new Test().start();
new Test().start();
for(int x=0; x<200; x++)
{
System.out.println("ThreadTest run"+x);
}
}
}
结果:
static Thread currentThread():获取当前线程对象
getName():获取线程名称
设置线程名称:setName或者构造函数
package Thread;
class Test extends Thread
{
//通过构造函数设置线程名
Test(String name)
{
super(name);
}
public void run()
{
for(int x=0; x<500; x++)
System.out.println("test run"+","+this.getName()+x);//通过this或者CurrentThread.getName()获取线程名
}
}
public class ThreadTest {
public static void main(String[] args) {
new Test("one...").start();
new Test("two....").start();
for(int x=0; x<200; x++)
{
System.out.println("ThreadTest run"+x);
}
}
}
结果:
2.创建线程的第二种方式:实现Runable接口
步骤:
1.定义类实现Runable接口
2.覆盖Runable接口中run方法。将线程要运行的代码存放在该run方法中
3.通过Thread类建立线程对象。
4.将Runable接口的子类对象作为实际参数传递给Thread类的构造函数。
为什么要将Runable接口的子类对象传递给Thread的构造函数。因为,自定义的run方法所属的对象是Runable接口的子类对象,所以要让线程去指定对象的run方法。就必须明确该run方法所属的对象。
5.调用Thread类的start方法开启线程并调用Runable接口子类的run方法。
示例:
/*
* 需求:简单的买票程序,多个窗口同时卖票
*/
package Thread;
class Ticket implements Runnable //创建一个类实现Runnable接口
{
private int tick=100;
//覆盖接口中的run方法
public void run()
{
while(true)
{
if(tick>0)
{
System.out.println(Thread.currentThread().getName()+"sale..."+tick--);
}
}
}
}
public class TicketTest {
public static void main(String[] args) {
Ticket t=new Ticket()//建立实现runnable接口的类的对象
Thread t1=new Thread(t);//创建Thread对象,并将实现类的对象作为参数传入构造函数中
t1.start(); //调用start()方法开启线程并运行run方法
Thread t2=new Thread(t);
t2.start();
Thread t3=new Thread(t);
t3.start();
Thread t4=new Thread(t);
t4.start();
}
}
输出结果:
实现方式和继承方式有什么区别呢?
实现方式好处:避免了单继承的局限性。在定义线程时,建议使用实现方式。
三.多线程的安全问题
还是四条线程卖票示例模拟线程安全问题:
package Thread;
class Ticket implements Runnable
{
private int tick=100;
public void run()
{
while(true)
{
if(tick>0)
{
try {
Thread.sleep(10); //让线程睡眠,模拟线程安全问题
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"sale..."+tick--);
}
}
}
}
public class TicketTest {
public static void main(String[] args) {
Ticket t=new Ticket();
Thread t1=new Thread(t);
t1.start();
Thread t2=new Thread(t);
t2.start();
Thread t3=new Thread(t);
t3.start();
Thread t4=new Thread(t);
t4.start();
}
}
输出结果:
发现:打印出0,-1,等错票,说明多线程的运行出现了安全问题
问题的原因:
当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线 程参与进来执行,导致共享数据的错误
解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行。
java对于多线程的安全问题提供了专业的解决方式:同步代码块。
synchronized(对象)
{
需要被同步的代码
}
加锁示例:
package Thread;
class Ticket implements Runnable
{
private int tick=100;
Object obj=new Object();
public void run()
{
while(true)
{
synchronized(obj){
if(tick>0)
{
try {
Thread.sleep(10); //让线程睡眠,模拟线程安全问题
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"sale..."+tick--);
}
}
}
}
}
public class TicketTest {
public static void main(String[] args) {
Ticket t=new Ticket();
Thread t1=new Thread(t);
t1.start();
Thread t2=new Thread(t);
t2.start();
Thread t3=new Thread(t);
t3.start();
Thread t4=new Thread(t);
t4.start();
}
}
输出结果:
对象如同锁,持有锁的进程可以在同步中执行。没有持有锁的进程及时获取cpu的
执行权,也进不去,因为没有获取权限。
同步的前提:
1.必须要有两个或两个以上的线程。
2.必须是多个线程使用同一个锁。
3.必须保证同步中只能有一个线程在运行。
好处:解决了多线程的安全问题。
弊端:多个线程需要判断锁,较为消耗资源。
同步函数
package Thread;
/*
* 需求:
* 银行有一个金库。有两个储户分别存300元,每次存100,存10次。
* 目的:该程序是否有安全问题,如果有,如何解决
*
* 如何找问题:
* 1,明确哪些代码是多线程运行代码
* 2.明确共享数据
* 3.明确多线程运行代码中哪些语句是操作共享数据的。
*/
class Bank
{
private int sum;
public synchronized void add(int n) //同步函数
{
sum=sum+100;
System.out.println("sum="+sum);
}
}
class Cus implements Runnable
{
Bank b=new Bank();
public void run()
{
for(int x=0; x<11; 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。
静态函数使用的锁:
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件(类名.class)对象,该对象的类型是class,静态的同步方法使用的锁是该方法所在类的字节码文件对象
多线之应用:懒汉式:
package Thread;
class Single
{
private static Single s=null;
private Single(){};
public static Single getSingle()
{
//双重判断,提高效率
if(s==null)
{
//通过所解决线程安全问题
synchronized(Single.class)
{
if(s==null)
{
s=new Single();
}
}
}
return s;
}
}
public class SingleDemo {
public static void main(String[] args) {
Single.getSingle();
}
}
package Thread;
/*
* 死锁
*/
class Testlock implements Runnable
{
private boolean flag;
Testlock(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{
synchronized (Lock.locka)
{
System.out.println("if locka");
synchronized (Lock.lockb)
{
System.out.println("if lockb");
}
}
}
else
synchronized (Lock.lockb)
{
System.out.println("else lockb");
synchronized (Lock.locka)
{
System.out.println("else locka");
}
}
}
四.多线程通信
package Thread;
//定义一个资源
class Res
{
String name;
String sex;
}
//定义类输入资源
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.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女女女女女";
}
x=(x+1)%2;
}
}
}
//定义类输出资源
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run() {
while(true)
{
System.out.println(r.name+"..."+r.sex);
}
}
}
public class IntOutputDemo {
public static void main(String[] args) {
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in); //输入线程
Thread t2=new Thread(out);//输出线程
t1.start();//开启输出线程并运行run方法
t2.start();//开启输出线程并运行run方法
}
}
输出结果:
从结果可见多线通信存在安全问题
解决安全问题:加锁
//定义一个资源
class Res
{
String name;
String sex;
}
//定义类输入资源
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized (r) {
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女女女女女";
}
x=(x+1)%2;
}
}
}
}
//定义类输出资源
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run() {
while(true)
{
synchronized (r) {
System.out.println(r.name+"..."+r.sex);
}
}
}
}
public class IntOutputDemo {
public static void main(String[] args) {
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in); //输入线程
Thread t2=new Thread(out);//输出线程
t1.start();//开启输出线程并运行run方法
t2.start();//开启输出线程并运行run方法
}
}
结果:
等待唤醒机制
wait(); 等待
notify(); 唤醒
notifyAll(); 唤醒全部
这些都使用在同步中,因为要对持有监视器(锁)的线程操作。所以要使用在同步中,因为只有同步才具有锁。
为什么这些操作线程方法要定义在Object类中呢?
因为这些方法在操作同步中的线程时,都必须要标示它们所操作线程持有的锁,只有同一个锁的
被等待线程,可以被同一个锁上notify唤醒。不可以对不同锁中线程进行唤醒。也即是说等待和
唤醒必须是同一个锁。而锁可以是任意对象,所以可以被任意对象调用的方法定义在object类中。
示例:
package Thread;
//定义一个资源
class Res
{
String name;
String sex;
boolean flag=false;
}
//定义类输入资源
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized (r) {
if(r.flag)
try {
r.wait(); //等待
} catch (InterruptedException e) {}
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女女女女女";
}
x=(x+1)%2;
r.flag=true;
r.notify(); //唤醒
}
}
}
}
//定义类输出资源
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run() {
while(true)
{
synchronized (r) {
if(!r.flag)
try {
r.wait();//等待
} catch (InterruptedException e) {}
System.out.println(r.name+"..."+r.sex);
r.flag=false;
r.notify();//唤醒
}
}
}
}
public class IntOutputDemo {
public static void main(String[] args) {
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in); //输入线程
Thread t2=new Thread(out);//输出线程
t1.start();//开启输出线程并运行run方法
t2.start();//开启输出线程并运行run方法
}
}
结果:
优化代码:
package Thread;
//定义一个资源
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;
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try {this.wait();} catch (Exception e) {
}
System.out.println(name+"........"+sex);
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();
}
}
}
public class IntOutputDemo {
public static void main(String[] args) {
Res r=new Res();
//用匿名对象简化代码
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
/*
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in); //输入线程
Thread t2=new Thread(out);//输出线程
t1.start();//开启输出线程并运行run方法
t2.start();//开启输出线程并运行run方法
*/
}
}
输出结果
示例二:生产者与消费者
package Thread;
public class ProduceConsumerDemo {
public static void main(String[] args) {
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con =new Consumer(r);
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 {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name=name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
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();
}
}
}
对于多个生产者和消费者,为什么要定义while判断标记
原因:让被唤醒的线程再一次判断标记。
为什么要定义notifyAll
因为需要唤醒对方的线程,只有notify,容易出现只唤醒本方线程的情况,导致程序中所有线程等待。
JDK1.5中提供了多线程升级解决方案,将同步synchronized替换成现实lock操作,将object中的wait,
notify notifyAll,替换了Condition对象,该对象可以Lock锁,进行获取。
实例代码:
package Thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProduceConsumerDemo {
public static void main(String[] args) {
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con =new Consumer(r);
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;
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) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run() {
while(true)
{
try {
res.out();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
停止线程:
开启多线程运行,运行代码通常是循环结构,只要控制住循环,就可以让run方法结束,也就是线程结束。
特殊情况:
当线程处于冻结状态,就不会读取到标记,那么线程就不会结束,当没有指定的方式让冻结的线程恢复到运行状态是,这时就需要对冻结进行清除,强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。
Thread 类中interrupt()方法。
示例:
package Thread;
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;
}
}
public 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)
{
//st.changeFlag();
t1.interrupt();//让t1继续运行
t2.interrupt();
break;
}
System.out.println( Thread.currentThread().getName()+"....."+num);
}
System.out.println("over");
}
}
结果:
几个Thread类中方法:
void setDaemon(boolean on)
将该线程标记为守护线程或用户线程。
void join()
等待该线程终止。
当A线程执行到了B线程的.join()方法时,A就会等待,等B线程都执行完,A才会执行,join可以用来临时加入线程执行。
void setPriority(int newPriority)
更改线程的优先级。