您的位置:首页 > 职场人生

黑马程序员-----Java基础-----线程与同步

2015-08-16 06:43 387 查看
 -----<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

线程与同步:

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

该进程中至少一个线程负责java程序的执行

而且这个线程运行的代码存在于main方法中。

该线程称之为 主线程

扩展:其实更细节说明jvm启动 不止一个线程还有负责垃圾回收机制的线程。

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

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

创建线程的第一种方式,继承Thread类。

1,定义类继承Thread

2,复写Thread中的run方法。

3,调用线程start方方法

该方法两个作用,启动线程,调用rnu方法。

发现运行结果每次都不同,因为多个线程都在获取CPU执行使用权,CPU执行到谁

谁就运行。

明确一点 在某一时刻,只能一个程序运行,(多核除外)

cpu在做着快速切换,以达到看上去同时运行的效果。

多线程的一个特性:随机性,谁抢到谁执行,至于执行多长,cpu说的算。

class Demo extends Tread

{
public void run()
{
System.out.println("demo run");
}

}

public class ThreadDemo {

public static void main(String[] args) {
Demo d = new Demo();//创建好一个线程
//d.run();仅仅是对象调用方法,线程创建了,并没有运行。
d.start();//开启线程并执行该线程的run方法。
}

}

为什么要覆盖run方法?xx重要

目的:将自定义的代码存储在run方法,让线程运行。

Thread类用于描述线程

该类就定义了一个功能,用于存贮线程运行的代码,该存储功能就是run方法。

也就是说Thread类中的run方法,用于存储线程中要运行的代码。

run和start区别

run按顺序执行

start同时执行

线程运行状态

被创建--》start()-->运行--》sleep(time)--》冻结(sleep时间到了冻结结束)

被创建--》start()-->运行--》wait()--》冻结(不会自动回来)--notify唤醒

被创建--》start()-->运行--》stop()消亡

线程都有自己的名称。

Thread-编号 从0开始

static Thread currentThread():获取当前对象

getName(); 获取线程名称。

设置线程名称;serName或者构造函数。

class Test extends Thread

{
Test(String name)
{
super(name);//this.name = name;
}
public void run()
{
for(int x = 0 ;x < 60 ; x++)
{
System.out.println(Thread.currentThread().name+x);//this.getname();
}
}

}

class ThreadTest

{
public static void main(String[] args)
{
Test t1 = new Test("one===");
Test t2 = new Test("two---");
t1.start();
t2.start();
}

}

需求:简单的卖票程序

多窗口买票。

class Tick implements Runnable

{
private static  int tick = 100;//static修饰只初始化一次
public void run()
{
while(true)
{
if(tick > 0)
{
System.out.println(Thread.currentThread().getName()+"---"+tick--);
}
}
}

}

class TickDemo

{
public static void main(String[] args)
{
Tick t = new Tick();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);

t1.start();
t2.start();
t3.start();
t4.start();
}

}

创建线程第二种方法;实现Runnable接口

步骤:

1.定义类实现Runable接口

2.覆盖Runnable接口中的run方法

将线程要运行的代码存放在该run方法中

3,通过Thread类建立线程对象

4.将Runnable接口的子类对象作为实现参数传给Thread类的构造函数

为什么要将Runnable接口的子类对象传递给Thread的构造函数

因为自定义的run方法所属的对象是Runnable接口的子类对象。

所以要让线程去指定指定对象的run方法。就必须明确该run方法所属对象。

5.调用Thread类的方法开启线程并调用Runnable接口子类的run方法。

实现方式和继承方式的区别?XX重要

线程代码存放位置不同

继承Thread:存放在Thread子类run方法中

实现Runnable:存放在接口的子类的run方法。

实现方法避免了单继承的局限性

在定义线程时,建议使用实现方式。

通过分析,发现,打印出0 -1 -2等结果

 多线程的运行出现了安全问题

  

 问题的原因

  当多条语句在操作同一个线程共享数据,一个线程对多条语句只执行了一部分

  还没有执行完,另一个线程参与进来执行,导致共享数据的错误。

 

 解决办法:

  对多条操作共享数据的语句,只能让一个线程都执行完

  在执行过程中,其他线程不可以参与执行。

 

 java对于多线程的安全问题提供了专业的解决方式。

 就是同步代码块

 synchronized(对象)

 

 对象如同锁。持有锁的线程可以在同步中执行

 没有持锁的线程及时获得cup的执行权,也进不去,因为没有获取锁。

 相当于火车上的卫生间--经典。

 

 同步的前提

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

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

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

 好处

  解决了多线程的安全问题

 弊端

  多个线程需要判断锁,比较耗费资源;

class Tick implements Runnable

{
private   int tick = 100;//static修饰只初始化一次
Object obj =new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(tick > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"---"+tick--);
}
}
}
}

}

class TickDemo

{
public static void main(String[] args)
{
Tick t = new Tick();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);

t1.start();
t2
165e2
.start();
t3.start();
t4.start();
}

}

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

目的;程序是否有安全问题,如何解决。

class Bank

{
private int sum;
public void add(int n)
{
sum = sum + n;
System.out.println(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

{
Cus c = new Cus();
Thread t1 = new Thread();
Thread t1 = new Thread();
t1.start();
t2.start();

}

如何找问题:

1,明确哪些代码是多线程运行代码。

2,明确共享数据。

3,明确多线程运行代码中哪些语句是操作共享数据。

class Bank

{
private int sum;
Object obj = new Object();//随便创建一个对象
public void add(int n)//这里可以抛,throws---可以用同步函数更方便不需要上一步创建对象了。public void synchronized add(int n)
{
synchronized(obj)//同步代码块,操作共享数据。
{
sum = sum + n;
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(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

{
Cus c = new Cus();
Thread t1 = new Thread();
Thread t1 = new Thread();
t1.start();
t2.start();

同步函数用的是哪个锁?

  函数需要被对象调用,那么函数都有一个所属对象引用,就是this

  所属同步函数使用的锁是this。

  

  通过该程序进行验证

  

  使用两个线程来买票

  一个线程在同步代码块中。

  一个线程在同步函数中。

  都在执行买票动作。

  

  class Tick implements Runnable

  {

  private   int tick = 100;//static修饰只初始化一次

  Object obj =new Object();

  boolean flag = true;

  public void run()

  { 

 

  if(flag)

  {
  while(true)
  {
  synchronized(this)//括号里用obj是错误的,用this是对的。
  {
  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()//this

  {

  if(tick <0)

  {

  try{Thread.sleep(10);}catch(Exception e){}

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

  }

  }

  }

 class TickDemo

 {

  public static void main(String[] args)

  {

  Tick t = new Tick();

  Thread t1 = new Thread(t);

  Thread t2 = new Thread(t);

   

  t1.start();

  t2.start();

  }

 }

如果同步函数被静态修饰后,是用什么锁呢?

通过验证不是this,因为静态方法中,也不可以定义this。

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

类名.class  该对象的类型是class。

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

类名.class

class Tick implements Runnable

{
private static  int tick = 100;//static修饰只初始化一次
boolean flag = true;
public void run()


if(flag)
{
  while(true)
  {
  synchronized(Tick.class)//这里类名.class。

public static synchronized void show()//static修饰
{
if(tick <0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"-show--"+tick--);   
}
}

 

单利设计模式

饿汗式:

class Single

{
private static Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;

}

}

懒汉式

class Single

{
private static Single s= null;
private Single(){}
public static Single getInstrance()
{
if(s==null)
s = new Single;
return s;
}

}

---

class Single

{
private static Single s= null;
private Single(){}
public static synchronized Single getInstrance()
{
if(s==null)
s = new Single;
return s;
}

}

---

class Single

{
private static Single s= null;
private Single(){}
public static  Single getInstrance()
{
if(s==null)
{
synchronized(Single.class)//静态方法,不能用this,双重if判断,减少锁运行次数。
if(s==null)
s = new Single;
return s;
}
}

}

上面锁的类型是字节码文件对象

死锁。

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("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

{
static Object locka =new Object();
static Object lockb =new Object();

}

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();
}

}

重要

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(Exception 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(Exception e){}
System.out.println(r.name+"---"+r.sex);r.flag = true;
r.flag = false;
r.notify();
}
}
}

}

class Test

{
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();
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");
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 Test

{
public static void main(String [] args)
{
Res r = new Res();

new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}

}

生产消费者

class Resource

{
private String name;
private int count = 1;
private boolean flag = false;
// t1 t2
public synchronized void set(String name)
{
while(flag)//用if不会每次都判断标记
try{this.wait();}catch(Exception e){}//t1 t2
this.name = name+"-----"+count++;
System.out.println(Thread.currentThread().getName()+"=生产者="+this.name);
flag = true;
this.notifyAll();//注意

}
//t3  t4
public synchronized void out()
{
while(!flag)
try{this.wait();}catch(Exception e){}//t3  t4
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 Test

{
public static void main(String[] args)
{
Resource r = new Resource();

Producer p = new Producer(r);

Consumer c = new Consumer(r);

Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);

t1.start();
t2.start();
t3.start();
t4.start();
}

}

notify用于两个线程

notifAll 用于多个线程(不用all就会出现所有线程等待中,)

if用于2个线程(用于多线程会出现生产者连着2个或消费者连着2个的情况。不安全。不会判断标记)

while用于多个线程

对于多个生产和消费者

为什么要定义while判断标记

因为:让被唤醒的线程再一次判断标记。

为什么要定义notifyall

因为需要唤醒对方线程

因为只要用notify ,容易出现只唤醒本方线程的情况,导致所有线程都等待。

用lock();,unlock();,signal,signalAll,await,Condition();

import java.util.concurrent.locks.*;

class Resource

{
private String name;
private int count = 1;
private boolean flag = false;
public Lock lock =new ReentrantLock();
private Condition c_pro = lock.newCondition();
private Condition c_con = lock.newCondition();
public void set(String name) throws Exception
{
lock.lock();
try
{
while(flag)
c_pro.await();
this.name = name+"-----"+count++;
System.out.println(Thread.currentThread().getName()+"=生产者="+this.name);
flag = true;
c_con.signal();
}
finally
{
lock.unlock();
}

}
public synchronized void out()throws Exception
{
lock.lock();
try
{
while(!flag)

c_con.await();
System.out.println(Thread.currentThread().getName()+"----消费者----"+this.name);
flag = false;
c_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(Exception e)
{

}
}

}

class Consumer implements Runnable

{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.out();
}
catch(Exception e)
{

}

}
}

}

class Test

{
public static void main(String[] args)
{
Resource r = new Resource();

Producer p = new Producer(r);

Consumer c = new Consumer(r);

Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);

t1.start();
t2.start();
t3.start();
t4.start();
}

}

stop方法已经过时。

如何停止线程?

只有一种,run方法结束。

开启多线程运行,运行代码通常是循环结构。

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

特殊情况

当线程处于了冻结状态

就不会读取到标记,那么线程就不会结束。

当没有指定的方式让冻结的线程回复到运行状态时,这时需要对冻结进行清除。

强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。

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

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;//qiangzhi
}
System.out.println(Thread.currentThread().getName()+"---run");
}
}
public void changeFlag()
{
flag = false;
}

}

class Test

{
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)
{
t1.interrupt();
t2.interrupt();
//st.changeFlag();
break;
}
System.out.println(Thread.currentThread().getName()+"---"+num);
}
System.out.println("over");
}

}

线程守护

class StopThread implements Runnable

{
private boolean flag = true;
public  void run()
{
while(flag)
{
System.out.println(Thread.currentThread().getName()+"---run");
}
}
public void changeFlag()
{
flag = false;
}

}

class Test

{
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++==60)
{
//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可以用来临时加入线程执行。

tb.start();

ta.start();

b.join();

线程优先级

1-10 十级

t1.setPriority(Thread.MAX_PRIORITY);

yield();临时停止

Thread.yield();

开发如何写线程:

class ThreadTest

{
public static void main(String [] args)
{
for(int x = 0;x < 100 ;x++)
{
System.out.println(Thread.currentThread().getName());
}

for(int x = 0;x < 100 ;x++)
{
System.out.println(Thread.currentThread().getName());
}

for(int x = 0;x < 100 ;x++)
{
System.out.println(Thread.currentThread().getName());
}
}

}

 简便写法

class ThreadTest

{
public static void main(String [] args)
{
new Thread()
{
for(int x = 0;x < 100 ;x++)
{
System.out.println(Thread.currentThread().getName());
}
}.start();

for(int x = 0;x < 100 ;x++)
{
System.out.println(Thread.currentThread().getName());
}

Runnable ra =new Runnable()
{
public void run()
{
for(int x = 0;x < 100 ;x++)
{
System.out.println(Thread.currentThread().getName());
}
}
};
new Thread(ra).start();
}

}

三个线程同时运行,高效。单独封装。

  -----<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: