1.1 同步
多个操作在同一时间内 只能有一个线程运行,其他线程要等此线程完成之后才能继续执行。
要解决资源共享的同步操作问题,可以使用同步代码块和同步方法完成。
1.1 同步代码块
代码块分四种:
(1) 普通代码块:是直接定义在方法之中的。
(2)构造块:是定义在类中的,优先于构造方法执行,可以重复调用
(3)静态块:是使用static关键字声明,又相遇构造块执行,只执行一次
(4)同步代码块:使用synchronized关键字声明,为同步代码块
格式
synchronized(同步对象)//当前对象作为同步对象 使用this表示
{
需要同步的代码
}
class MyThread implements Runnable
{
public int ticket = 5 ; //定义票的数量
public void run() //覆写run()方法
{
for(int i=0;i<100;i++)
{ synchronized(this) //同步代码块 对当前对象进行同步
{
if(ticket>0) //如果还有票
{
try
{
Thread.sleep(2000) ;//时间延迟
}
catch (InterruptedException e)
{
e.printStackTrace() ;
}
System.out.println("卖票 ticket:"+ ticket--) ;
}
}
}
}
}
public class SyncDemo01
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ;//实例化线程对象
Thread t1 = new Thread(mt) ; //定义Thread对象
Thread t2 = new Thread(mt) ; //定义Thread对象
Thread t3 = new Thread(mt) ; //定义第三个售票员
t1.start() ; //启动线程
t2.start() ; //开始卖票
t3.start() ; //启动线程
}
}
使用同步操作,不会出现负数,但是程序执行效果下降
1.2 同步方法
使用synchronized关键字将一个方法声明成同步方法
格式
synchronized 方法返回值 方法名称(参数列表){}
class MyThread implements Runnable
{
public int ticket = 5 ; //定义票的数量
public void run() //覆写run()方法
{
for(int i=0;i<100;i++)
{
this.sale() ; //调用同步方法
}
}
public synchronized void sale() //声明同步方法 卖票
{
if(ticket>0) //如果还有票
{
try
{
Thread.sleep(2000) ;
}
catch (InterruptedException e)
{
e.printStackTrace() ;
}
System.out.println("卖票 ticket:"+ ticket--) ;
}
}
}
public class SyncDemo02
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ;//实例化线程对象
Thread t1 = new Thread(mt) ; //定义Thread对象
Thread t2 = new Thread(mt) ; //定义Thread对象
Thread t3 = new Thread(mt) ; //定义第三个售票员
t1.start() ; //启动线程
t2.start() ; //开始卖票
t3.start() ; //启动线程
}
}
2 死锁
A 资源共享的时候需要进行同步操作
B 程序中过多的同步会产生死锁
死锁 一般情况下就是表示 在互相等待 。
3线程生命周期
修改标记位 来 停止线程
class MyThread implements Runnable
{
private boolean flag = true ; //定义标记位
public void run() //覆写run()方法
{
int i = 0 ;
while(this.flag) //this表示当前对象
{
System.out.println(Thread.currentThread().getName()
+"运行,i"+(i++)) ;
}
}
public void stop() //定义stop方法
{
this.flag = false ; //修改标记位
}
}
public class ThreadStopDemo01
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ; //实例化MyThread对象
Thread t = new Thread(mt,"当前线程名称") ; //声明Thread线程对象
t.start() ; //启动线程
try
{
Thread.sleep(30) ;
}
catch (InterruptedException e)
{
e.printStackTrace() ;
}
mt.stop() ; //停止线程 //对象.方法()
}
}