进程
是一个正在执行中的程序。
每个进程执行都有一个执行顺序,该顺序是一个执行路径,或者叫一个控制单元。
举例子:一个进程,就是一个正在运行的程序。
线程
就是进程中的一个独立的控制单元。
线程在控制着进程的执行。
举例子:例如生产流水线,一个厂房如果只有一条流水线,只能是产品生产完一个再生产一个。如果多装几条流水线,就可以同时生产多个,这样提高了效率,每一条流水线,就可以理解为一个线程。
一个程序中至少有一个线程。
java vm 启动的时候会有一个进程java.exe。
该进程中至少有一个线程负责java程序的执行。
而且这个线程运行的代码存在于main方法中。
该线程称之为主线程。
扩展:其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程。
Thread类
创建线程的第一种方式,:继承Thread类。
步骤:
1,定义类继承Thread。
2,复写Thread类中的run方法。
目的:将自定义的代码存储在run方法中,让线程运行
3,调用线程的start方法
该方法有两个作用,启动线程,调用run方法。
class Demo extends Thread
{
public void run()
{
for (int x=0;x<60 ;x++ )
System.out.println("demo run"+x);
}
}
class Test
{
public static void main(String[] args)
{
Demo d = new Demo(); //创建一个对象,就是创建一个线程
d.start(); //开启线程并执行该线程的run方法。
//d.run; //仅仅是对象调用方法,而线程创建类,并没有运行。
for (int x=0 ; x<60 ;x++ )
System.out.println("hahah------"+x);
}
}
发现运行结果每次都不一样。
因为多个线程都在获取CPU的执行权,cpu执行到谁,谁就运行。
明确一点,在某一时刻,只能有一个程序在运行。(多核除外)
cpu在做着快速的切换,已达到看上去是同时运行的效果。
我们可以形象把多线程的运行行为在互相抢夺cpu的执行权。
这就是多线程的一个特性:随机性,谁抢到谁执行,至于执行多长,由cpu说的算。
为什么要覆盖run方法呢?
Thread类用于描述线程。
该类就定义了一个功能,用于存储线程要运行的代码,该存储功能就是run方法。
也就是说Thread类中的run方法,用于存储线程要运行的代码。
/*
联系
创建两个线程,和主线程交替运行。
*/
class A extends Thread
{
private String name;
A(String name)
{
this.name=name;
}
public void run()
{
for (int x=0;x<10 ;x++ )
{
System.out.println(name+"+"+x);
}
}
}
class Test
{
public static void main(String[] args)
{
A a1 = new A("one");
A a2 = new A("two");
a1.start();
a2.start();
for (int x=0 ; x<10 ;x++ )
System.out.println("hahah------"+x);
}
}
临时状态(阻塞)
具备执行资格,但是没有执行权
^
^ sleep(time)
| —————————————————>>>
| sleep(时间到)
start() | <<<—————————————————
被创建——————————>>> 运行 wait() 冻结
| —————————————————>>> 没有执行资格
| notify()
stop(); | <<<—————————————————
run方法结束 |
V
V
消亡
线程都有自己默认的名称
this.getName() 获取线程名
Thread-编号 ,该编号从0开始。
class A extends Thread
{
public void run()
{
for (int x=0;x<10 ;x++ )
{
System.out.println(this.getName()+"-----"+x); //getName获取线程名
}
}
}
class Test
{
public static void main(String[] args)
{
A a1 = new A();
A a2 = new A();
a1.start();
a2.start();
for (int x=0 ; x<10 ;x++ )
System.out.println("hahah------"+x);
}
}
自定义Thread名称
class A extends Thread
{
A(String name)
{
super(name); // 传给父类名称
}
public void run()
{
for (int x=0;x<10 ;x++ )
{
System.out.println(this.getName()+"-----"+x); //获取名称
}
}
}
class Test
{
public static void main(String[] args)
{
A a1 = new A("ONE");
A a2 = new A("TWO");
a1.start();
a2.start();
for (int x=0 ; x<10 ;x++ )
System.out.println("hahah------"+x);
}
}
(static Thread) currentThead(); 获取当前线程对象
getName(); 获取线程名称。
设置线程名成: setName 或者 构造函数(直接 super(name) )。
class A extends Thread
{
A(String name)
{
super(name);
}
public void run()
{
for (int x=0;x<10 ;x++ )
{
System.out.println((Thread.currentThread()==this)+"-----"+this.getName()+"----"+x);
}
}
}
class Test
{
public static void main(String[] args)
{
A a1 = new A("ONE");
A a2 = new A("TWO");
a1.start();
a2.start();
for (int x=0 ; x<10 ;x++ )
System.out.println("hahah------"+x);
}
}
Runnable接口
创建线程的第二种方法 : 实现Runnable接口
为什么要有Runnable:因为在实际情况中,有可能出现一个类已经是子类,已经继承了别的类,这时可能需要多线程的应用。由于java中单继承的特性,所以设计出Runnable接口,用于解决继承类父类的情况下,实现多线程的情况
步骤:
1,定义类实现Runnable接口。
2,覆盖Runnable接口中的run方法。
将线程要运行的代码放在该run方法中。
3,通过Thread类建立线程对象。
4,将Runnalbe接口的子类对象作为实际参数传递给Thread类的构造函数.
为什么要将Runnable接口的子类对象传递给Thread的构造函数。
因为,自定义的run方法所属的对象是Runnable接口的子类对象。
所以要让线程去执行指定对象的run方法。就必须明确该run方法的所属对象。
5,调用Thread类的start方法开启线程并调用Runnable接口子类中的run方法。
/*
需求:简单的卖票程序。
多个窗口买票。
*/
class Ticket implements Runnable
{
private int tick = 100;
public void run()
{
while(true)
{
if(tick>0)
System.out.println(Thread.currentThread().getName()+"---sale:"+tick--);
}
}
}
class Test
{
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();
}
}
Runnable实现方式和Thread继承方式的区别
继承Thread:只能单继承,线程代码存放在Thread子类的run方法中。
实现Runnable:可以避免单继承的局限性,线程代码存放在Runnable接口的子类的run方法中。
多线程的安全问题
问题原因:
当多条语句在操作同一个线程共享数据时,一个线程对多条语句执行了一部分,没有执行完。
另一个线程参与进来执行,导致共享数据的错误。
解决办法:
对多条操作共享数据的语句,只能让一个线程执行完,在执行过程中,其他线程不可以参与执行。
java对于多线程的安全问题提供类专业的解决方式。
就是同步代码块。
synchronized (对象)
{
需要被同步的代码;
}
对象如同锁,持有锁的线程可以在同步中执行。
没有持有锁的线程即使获取cpu的执行权,也进不去,因为没有获取门锁。
如果火车上的卫生间。
同步的前提
1,必须要有两个或者两个以上的线程。
2,必须是多个线程使用同一个锁。
必须保证同步中只有一个线程在运行。
好处:解决了多线程的安全问题。
弊端:多个线程都需要判断锁,较为消耗资源。
class Ticket implements Runnable
{
private int num = 100;
Object obj = new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(num>0)
{
try{Thread.sleep(10);}catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....sale...."+num--);
}
}
}
}
}
class TicketDemo
{
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();
如何找安全问题:
1,明确哪些代码是多线程运行代码。
2,明确共享数据。
3,明确多线程运行代码中哪些语句是操作共享数据的。
class Bank
{
private int sum;
public synchronized void add(int n)
{
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 Test
{
public static void main (String[] args)
{
Cus s= new Cus();
Thread s1= new Thread(s);
Thread s2= new Thread(s);
s1.start();
s2.start();
}
}
同步代码块
class Bank
{
private int sum;
Object obj = new Object();
public void add(int n)
{
synchronized()
{
sum+=n;
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
System.out.println("sum="+sum);
}
}
}
同步函数
class Bank
{
private int sum;
Object obj = new Object();
public void synchronized add(int n)
{
sum+=n;
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
System.out.println("sum="+sum);
}
}
同步函数用的是哪一个锁?
函数需要被对象调用,那么函数都有一个所属对象引用,就是this。
所以同步函数使用的锁是this。
验证
一个线程在同步代码块中,
一个线程在同步函数中。
都在执行买票动作。
class Ticket implements Runnable
{
private int tick = 100;
boolean flag = true;
public void run()
{
if (flag)
{
while(true)
{
synchronized (this)
{
if(tick>0)
{
try{Thread.sleep(10);}catch (InterruptedException 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 (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....show...."+tick--);
}
}
}
class Test
{
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(10);}catch (Exception e){}
t.flag = false;
t2.start();
}
}
static修饰同步函数
如果同步函数被静态修饰后,使用的锁匙class对象。
验证发现,不是this,因为静态方法中不可以定义this。
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 。 该对象的类型是calss。
静态的同步方法,使用的锁是 该方法所在类的字节码文件对象。 类名.class
class Ticket implements Runnable
{
private static int tick = 100;
boolean flag = true;
public void run()
{
if (flag)
{
while(true)
{
synchronized (Ticket.class) // 锁为 类名.class
{
if(tick>0)
{
try{Thread.sleep(10);}catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....code...."+tick--);
}
}
}
}
else
while(true)
show();
}
public static synchronized void show() // static修饰 synchronized
{
if(tick>0)
{
try{Thread.sleep(10);}catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....show...."+tick--);
}
}
}
单例设计模式--懒汉式
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;
}
}
class SingleDemo
{
public static void main(String [] args)
{
Single s1=Single.getInstance();
Single s2=Single.getInstance();
System.out.println(s1==s2);
}
}
死锁
同步中嵌套同步。
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("1");
synchronized (MyLock.Lockb)
{
System.out.println("2");
}
}
}
}
else
{
while(true)
{
synchronized (MyLock.Lockb)
{
System.out.println("3");
synchronized (MyLock.Locka)
{
System.out.println("4");
}
}
}
}
}
}
class MyLock
{
static Object Locka = new Object();
static Object Lockb = new Object();
}
class DeadlockTect
{
public static void main(String[] args)
{
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start();
}
}