java基础要点(12)-多线程

来源:互联网 发布:客户经理好用软件 编辑:程序博客网 时间:2024/05/19 20:59


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

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

一个进程中至少有一个线程

JAVA JVM 启动的时候会有一个进程java.exe

该进程中至少一个线程负责java程序的执行。
而且这个线程运行的代码存在于main方法中。
该线程称之为主线程

扩展:其实更细节说明JVM,JVM启动不止一个线程,还有负责

垃圾回收机制的线程

##############################
#第一重点:创建线程的两种方式#
##############################

1、如何在自定义的代码中,自定义一个线程呢?

通过对API的查找,java已经提供了对线程这类事物的描述,就是Thread类

创建线程的第一种方式:继承Thread类。
步骤:
1、定义类继承Tread
2、复写Thread类中的run方法
目的是:将自定义代码存储在run方法中,让线程运行。
3、调用线程的start方法
该方法两个作用:启动线程,调用run方法

发现运行结果每一次都不同。
因为多个线程都获取CPU的执行权,CPU执行到谁,谁就运行。
明确一点,在某一个时刻,只能有一个程序在运行(多核除外)
CUP在做着快速的切换,已达到看上去是同时运行的效果
我们可以形象的把多线程的运行视为在互相抢夺CPU的执行权。

这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,CPU说了算

为什么要覆盖run方法呢?
Thread类用于描述线程
该类就定义了一个功能,用于存储线程要运行的代码。
该类存储功能就是run方法。
也就是说Thread类中的run方法,用于存储线程要运行的代码。

线程都有自己默认的名称
Thread-编号  该编号从0开始

static Thread currentThread();获取当前线程对象
getName():获取线程名称。

设置线程名称:setName或者构造函数

需求:简单的卖票程序
多个窗口同时买票

创建线程的第二种方式:实现Runnable接口

步骤:
1、定义类实现Runnable接口
2、覆盖Runnable接口中的run方法
将线程要运行的代码存放在该run方法中
3、通过Thread类建立线程对象
4、将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数

为什么要将Runnable接口的子类对象传递给Thread的构造函数
因为,自定义的run方法所属的对象是Runnable接口的子类对象
所以要让线程去指定对象的run方法,就必须明确该run方法所属对象
5、调用Thread类的start方法开启线程并调用Runnable类的run方法

实现方式和继承方式有什么区别呢?

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

两种方式区别:
继承Thread:线程代码存放在Thread子类run方法中
实现Runnable:线程代码存放在接口的子类的run方法中。

继承方式和实现方式的特点:
实现方式避免了单继承的局限性,所以创建线程建议使用第二种方式

线程的状态
1、被创建
2、运行
3、冻结
4、消亡

其实还有一种特殊的状态:临时状态

该临时状态的特点:
具备了执行资格,但不具备执行权

冻结状态的特点:
放弃了执行资格

##############################
#第二重点:同步的所有特性    #
##############################

通过分析,发现,打印出0的错票

多线程具备随机性,因为是由CPU不断的快速切换造成的,就有可能会产生多线程的安全问题。

问题的产生原因:
几个关键点:
1、多线程代码中有操作共享数据
2、多条语句操作该共享数据

当具备两个关键点时,有一个线程对多条操作共享数据的代码执行的一部分还没执行完,
另一个线程开始参与执行,就会发生数据错误

解决方法:
当一个线程在执行多条操作共享数据代码时,其他线程即使获取了执行权,也不可以参与操作。

Java就对这种解决方式提供了专业的代码
同步代码块:
synchronized(对象)
{
需要被同步的代码;
}


同步的原理:就是将部分操作功能数据的代码进行加锁
对象如同锁,持有锁的线程可以在同步中执行
没有持有锁的线程即使获取CPU的执行权,也进不去
因为没有获取锁。

火车上的卫生间-----经典案例

同步的前提:
1、必须要有两个或者两个以上的线程。
2、必须是多个线程使用同一个锁

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

同步的表现形式:
1、同步代码块
2、同步函数
两者有什么不同
同步代码块使用的锁是任意对象
同步函数使用的锁是this

注意:对于static的同步函数,使用的锁不是this,是类名.class 是该类的字节码文件对象

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

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

class Ticket  implements Runnable//extends Thread{private int tick = 100;//private String name;//Demo(String name)//{//super(name);//}public synchronized void run(){while(tick>0){try{Thread.sleep(10);}catch(Exception e){}//System.out.println((Thread.currentThread()==this)+"....."+this.getName                           ()+"....sale : "+ tick--);System.out.println(Thread.currentThread().getName()+"......"+tick--);}}}class ThreadDemo{public static void main(String[] args){//Demo d1=new Demo("one");创建好一个线程//Demo d2=new Demo("two");//d1.start();开启线程并执行该线程的run方法//d1.run();//仅仅是对象调用方法,而线程创建了,并没有运行//d2.start();Ticket d=new Ticket();Thread t1=new Thread(d);Thread t2=new Thread(d);t1.start();t2.start();}}


需求:
银行有一个金库,有两个储户分别存300元,每次存100,存三次。

目的:该程序是否有安全问题,如果有,如何解决?

如何找问题:
1、明确哪些代码是多线程运行代码
2、明确共享数据
3、明确多线程运行代码中哪些语句是操作共享数据的。


class Bank{private int sum;//Object obj=new Object();public synchronized void add(int n){//synchronized(obj)//{sum+=n;try{Thread.sleep(110);}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

通过该程序进行验证

使用两个线程来买票
一个线程在同步代码块中
一个线程在同步函数中
都在执行买票动作

class Tick implements Runnable{private int tick=100;Object obj=new Object();boolean flag=true;public void run(){if (flag){while (true){synchronized(this)//如果用obj锁的话出现错误票{if(tick>0){                                                try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName                                                   ()+"....show....."+tick--);}}}}elsewhile(true)show();}public synchronized void show()//这就是用的this锁{if (tick>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"....show....."+tick--);}}}class ThisLockDemo{public static void main(String[] args){Tick t=new Tick();Thread t1=new Thread(t);Thread t2=new Thread(t);t1.start();try{Thread.sleep(20);}catch(Exception e){}t.flag=false;t2.start();}}

如果同步函数被静态修饰后,使用的锁是什么呢?
通过验证,发现不再是this,因为静态方法中也不可以定义this

静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象
类名.class 该对象的类型是class

静态的同步方法,使用的锁是该方法所在类的字节码文件对象。

类名.class

上面例子中synchronized(Tick.class)就不是this

死锁
同步中嵌套同步

class MyLock{static Object locka=new Object();static Object lockb=new Object();}class Test implements Runnable{private boolean flag;Test(boolean flag){this.flag=flag;}public void run(){if (flag){while (true){synchronized(MyLock.locka){                                    System.out.println(Thread.currentThread().getName()+"....if..locka");synchronized(MyLock.lockb){                                              System.out.println(Thread.currentThread().getName()+"....if...lockb");}}}}else{while(true){synchronized(MyLock.lockb){System.out.println(Thread.currentThread().getName()+"...else...lockb");                                        synchronized(MyLock.locka){System.out.println(Thread.currentThread().getName()+"....else...locka");}}}}}}class DeadLockTest{public static void main(String[] args){Thread t1=new Thread(new Test(true));Thread t2=new Thread(new Test(false));t1.start();t2.start();}}


线程间通讯:
其实就是多个线程在操作同一个资源,但是操作的动作不同

wait();
notify();
notifyAll();

都使用在同步中,因为要对持有监视器(锁)的线程操作
所以要使用在同步中,因为只有同步才具有锁

为什么这些操作线程的方法要定义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;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");elser.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();/*Input in = new Input(r);Output out = new Output(r);Thread t1 = new Thread(in);Thread t2 = new Thread(out);t1.start();t2.start();*/}}


定义生产者与消费者

对于多个生产者和消费者
为什么要定义while判断标记
原因:让被唤醒的线程再一次判断标记

为什么定义notifyAll
因为需要唤醒对方线程,因为只用notify,容易出现只唤醒本方线程的情况,

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();}}}class ProducerConsumerDemo{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(con);Thread t3=new Thread(pro);Thread t4=new Thread(con);t1.start();t2.start();t3.start();t4.start();}}


JDK1.5中提供了多线程升级解决方案
将同步synchronized替换成显示的Lock操作
将Object中的wait,notify,notifyAll,替换了Condition对象
该对象可以Lock锁,进行获取
该示例中,实现了本方只唤醒对方操作

Lock:替代了Synchronized
lock
unlock
newCondition()

Condition:替代了Object wait notify notifyAll
await();
signal();
signalAll();


import java.util.concurrent.locks.*;class Resource2{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 Producer2 implements Runnable{private Resource2 res;Producer2(Resource2 res){this.res=res;}public void run(){while(true){try{res.set("+商品+");}catch (InterruptedException e){}}}}class Consumer2 implements Runnable{private Resource2 res;Consumer2(Resource2 res){this.res=res;}public void run(){while (true){try{res.out();}catch (InterruptedException e){}}}}class ProducerConsumerDemo2{public static void main(String[] args){Resource2 r=new Resource2();Producer2 pro=new Producer2(r);Consumer2 con=new Consumer2(r);Thread t1=new Thread(pro);Thread t2=new Thread(con);Thread t3=new Thread(pro);Thread t4=new Thread(con);t1.start();t2.start();t3.start();t4.start();}}


stop方法已经过时

如何停止线程?
只有一种,run方法结束
开启多线程运行,运行代码通常是循环结构

只要控制住循环,就可以让run方法结束,也就是线程结束

特殊情况:
当线程处于了冻结状态,就不会读取到标记,那么线程就不会结束

当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除。
强制让线程恢复到运行状态中,这样就可以操作标记让线程结束。

Thread类提供了该方法 interrupt();

守护线程
setDaemon(boolean b)
b=true 表示为守护线程
当正在运行的线程都是守护线程时,Java 虚拟机退出。 
该方法必须在启动线程前调用。 


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");}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.setDaemon(true);t2.setDaemon(true);t1.start();t2.start();int num=0;while (true){if (num++==100){t1.interrupt();//清除线程的冻结状态t2.interrupt();st.changeFlag();break;}System.out.println(Thread.currentThread().getName()+"......."+num);}System.out.println("over");}}

join:
当A线程执行到了B线程的join()方法时,A就会等待,等B线程都执行完,A才会执行。

join可以用来临时加入线程执行

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

setPriority()
改变线程的优先级
MAX_PRIORITY 最高优先级10
MIN_PRIORITY 最低优先级1
NORM_PRIORITY 默认优先级5

class Demo implements Runnable{public void run(){for (int x=1;x<99 ;x++ ){System.out.println(Thread.currentThread().getName()+"....."+x);}}}class JoinDemo{public static void main(String[] args)throws Exception{Demo d=new Demo();Thread t1=new Thread(d);Thread t2=new Thread(d);t1.start();t1.join();//插入线程t1.setPriority(Thread.MAX_PRIORITY);//最高优先级t2.start();for (int sum=0;sum<100 ;sum++ ){System.out.println(Thread.currentThread().getName()+"...."+sum);}}}class ThreadTest{public static void main(String[] args){new Thread (){public void run(){for (int x=0;x<100 ;x++ ){System.out.println(Thread.currentThread().getName()+"......"+x);}}}.start();for (int x=0;x<100 ;x++ ){System.out.println(Thread.currentThread().getName()+"......"+x);}Runnable r=new Runnable (){public void run(){for (int x=0;x<100 ;x++ ){System.out.println(Thread.currentThread().getName()+"......"+x);}}};new Thread(r).start();}}




class MyThread extends Thread{public void run(){try {Thread.currentThread().sleep(3000);} catch (InterruptedException e) {}System.out.println("MyThread running");}}public class ThreadTest{public static void main(String argv[])         {MyThread t = new MyThread();t.run();t.start();System.out.println("Thread Test");  }}代码分析过程:MyThread t = new MyThread();创建了一个线程。t.run();调用MyThread对象的run方法。这是只有一个线程在运行就是主线程。当主线程执行到了run方法中的sleep(3000);时。这是主线程处于冻结状态。程序并没有任何执行。当3秒过后,主线程打印了  MyThread running。 run方法执行结束。t.start();开启了t线程。有两种可能情况。第一种,主线程在只执行了t.start()后,还具有执行权,继续往下执行,打印了Thread Test。主线程结束。t线程获取执行权,调用自己的run方法。然后执行的sleep(3000);冻结3秒。3秒后,打印MyThread running t线程结束,整个程序结束。第二种情况:主线程执行到t.start();开启了t线程,t线程就直接获取到了执行权。就调用自己的run方法。指定到sleep(3000).t线程冻结3秒,这是t线程就是释放了执行权。那么主线程开始执行打印了Thread Test,主线程结束。等到3秒后,t线程打印MyThread running ,然后t线程结束。程序结束。



class test_parent{int x = 5;int y = 10;void set_value(int a, int b){x = a;y = b;}int get_1(){return this.x + this.y;}int get_2(){return x - y;}}class test_4 extends test_parent{int y;test_4(int a){y = a;}void set_value(int a, int b){x = a;y = b;}int get_2(){return y;}}class  Test2{public static void main(String[] args) {//test_4  a1=new test_4(1);//int x = a1.get_1();//System.out.println("x="+x);//x=15test_4  a1=new test_4(-1);a1.set_value(5,5);int x = a1.get_2();System.out.println("x="+x);//x=5}}








原创粉丝点击