(1)线程
进程:
是一个正在执行中的程序。 每一个进程执行都有一个执行顺序,该顺序是一个 执行路径,或者叫一个控制 单元。
线程:
就是进程中的一个独立的控制单元。线程在控制着进程的执行, 一个进程中至少有一个线程。
JAVA VM 启动的时候会有一个进程java.exe,该进程中至少一个线程负责java程序的执行,而且这个线程运行的代码存在于main方法中。该线程称之为主线程。
扩展:其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收线程
(2)如何在自定义的代码中,自定义一个线程呢?
通过对JDK API的查找,java已经提供了对线程这类事物的描述,就是Thread类。
创建线程有两种方式,第一种方式:继承Thread类。
步骤:
1,定义类继承Thread.
2,复写Thread类中的run方法。
3,调用线程的start方法,
该方法两个作用:启动线程,调用run方法
代码:
class Demo extends Thread
{
public void run()
{
for(int x = 0; x < 80; x++)
System.out.println("demo run-----"+x);
}
}
class ThreadDemo
{
public static void main(String[] args)
{
Demo d = new Demo();
//d.start();//开启线程并执行该线程的run方法。
d.run();// 仅仅是对象调用方法,而线程创建了,并没有运行。
for(int x = 0; x < 80; x++)
{
System.out.println("Hello World===="+x);
}
}
}
运行代码,发现运行结果每一次都不同?
因为多个线程都在获取cpu的执行权。cpu执行到谁,谁就运行,明确一点,在某一时刻,只能有一个程序在运行。(多核除外)
只不过cpu在做着快速的切换,以达到看上去是同时运行的效果。我们可以形象把多线程的运行行为认为在抢夺cpu的执行权。
这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,cpu说的算。
代码:
/*
练习:
创建两个线程,和主线程交替运行。
*/
class Test extends Thread
{
private String name;
Test(String name)
{
this.name = name;
}
public void run()
{
for(int x = 0; x < 60; x++)
System.out.println(name+"run..."+x);
}
}
class ThreadTest
{
public static void main(String[] args)
{
Test t = new Test("进程1");
Test t1 = new Test("进程2");
t.start();
t1.start();
for(int x = 0; x < 70; x++)
System.out.println("main...."+x);
}
}
第二种方式:实现Runnable接口,必须覆盖接口中的run()方法
好处:
(3)为什么要覆盖方法?
Thread类用于描述线程。
该类定义了一个功能,用于存储线程要运行的代码,该存储功能就是run方法。
也就是说Thread类中的run方法,用于存储线程要运行的代码。
(4)线程的四种状态:
(5)多线程例子
需求:简单的买票程序,多个窗口同时买票。
代码:
class Ticket implements Runnable
{
private static int tick = 100;
public void run()
{
while(true)
{
if(tick > 0)
System.out.println(Thread.currentThread().getName()+"...."+tick--);
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Runnable run = new Ticket();
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
Thread t3 = new Thread(run);
Thread t4 = new Thread(run);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
通过分析,发现,打印出0,-1,-2等错票
多线程的运行出现了安全问题。
1,问题的原因:
当多条语句在操作线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,
另一个线程参与进来执行。导致共享数据的错误。
2,解决办法:
对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行。
java对于多线程的安全问题提供了专业的解决方式。就是同步代码块。
(6)同步代码块
synchronized(对象)
{
需要被同步的代码
}
对象如同锁,持有锁的线程可以在同步中执行。
没有持有锁的线程即使获得cpu的执行权,也进不去,因为没有锁。
同步的前提:
1,必须要有两个或者两个以上的线程。
2,必须是多个线程使用同一个锁。
必须保证同步中只能有一个线程在运行。
好处: 解决了多线程的安全问题。
弊端:多个线程需要判断锁,较为消耗资源。
代码:
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(Exception e){}
System.out.println(Thread.currentThread().getName()+"..."+tick--);
}
}
}
}
}
class TicketDemo2
{
public static void main(String[] args)
{
Ticket t= new Ticket();
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();
}
}
案例:
需求:
银行有一个金库。有两个储户分别存300元,每次存100元,存3次。
目的:怎么找程序是否有安全问题,如果有,如何解决。
代码:
class Bank
{
//Object obj = new Object();
private int sum;
public synchronized void add(int n)
{
//synchronized(obj)
//{
sum = sum + n;
try{Thread.sleep(10);}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 cus = new Cus();
Thread t1 = new Thread(cus);
Thread t2 = new Thread(cus);
t1.start();
t2.start();
}
}
如何找问题:
1,明确那些代码是多线程运行代码
2,明确共享数据
3,明确多线程运行代码中那些语句是操作共享数据的。
(7)同步函数
上面的例子引入同步函数:
1,同步函数用的是哪个锁呢?
函数需要被对象调用,那么函数都有一个所属对象引用。就是this,所以同步函数使用的锁是this。
2,如果同步函数被静态修饰后,使用的锁是什么呢?
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 该对象的类型是Class
静态的同步方法,使用的锁是该方法所在类的字节码文件对象。类名.class
如:单例设计模式,懒汉式
class Single
{
private static Single s = null;
private Single(){}
public static Single getInstance ()//使用的锁是该方法所在类的字节码文件对象{
if(s==null)
{
synchronized(Single.class) //()//使用的锁是该方法所在类的字节码文件对象
{
if(s == null )
s = new Single();
}
}
return s;
}
}
(8)死锁现象
代码:
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)
{
synchronized(MyLock.locka)
{
System.out.println("if.....locka");
synchronized(MyLock.lockb)
{
System.out.println("if.....lockb");
}
}
}
else
{
synchronized(MyLock.lockb)
{
System.out.println("else.....lockb");
synchronized(MyLock.locka)
{
System.out.println("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();
}
}
(9)线程间的通信
线程间通讯:
其实就是多个线程在操作同一个资源,
但是操作的动作不同。
例子:生产者与消费者
代码1:
class ProduceConsumerDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
Produce pro = new Produce(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 Produce implements Runnable
{
private Resource res;
Produce(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 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();
}
}
对于多个生产者和消费者。
为什么要定义while判断标记。
原因:让被唤醒的线程再一次判断标记。
为什么定义notifyAll
因为需要唤醒对方线程
因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待
代码2:
import java.util.concurrent.locks.*;
class ProduceConsumerDemo2
{
public static void main(String[] args)
{
Resource res = new Resource();
Produce pro = new Produce(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 Produce implements Runnable
{
private Resource res;
Produce(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)
{
}
}
}
}
/*
JDK1.5 中提供了多线程升级解决方案,
同步synchronized替换成显示的Lock操作。
将Object中的wait,notify,notifyAll,替换了Condition对象
该对象可以通过Lock锁 进行获取。
该示例中,实现了本方只唤醒对方操作。
*/
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
private ReentrantLock 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();
}
}
}
(10)停止线程
如何停止线程?
只有一种,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()+"..Exceprtion");
flag = false;
}
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.start();
t2.start();
int num = 0;
while(true)
{
if(num++ == 60)
{
//st.changeFlag();
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()
+"....run.."+num);
}
System.out.println("over");
}
}