一、线程同步处理
1、解决同步问题的关键是锁,锁指的当某一个线程执行操作的时候,其他线程外面等待。换言之,所谓同步指多个操作在同一个时间段内只能有一个线程进行,其他线程要等待此线程完成之后才可以继续执行。
2、在程序中使用synchronized关键字来实现,利用此关键字可以定义同步方法或同步代码块,也就是在同步代码块中的代码只允许一个线程执行。
3、利用同步代码块执行处理:
synchronized(同步对象){
同步代码操作;
}
一般要进行同步对象处理的时候可以采用当前对象this操作。
4、使用同步的缺点
加入同步后,会使程序的整体性能下降,也就是程序的执行时间会延长。
范例:利用同步代码块解决数据同步问题
class MyThread implements Runnable{
private ticket =10; // 有10张票
@Override
public void run(){
while(true){
// 同步代码块
synchronized(this){ // 同步锁,一次只允许一个线程执行
if(this.ticket > 0){
System.out.printIn(Thread.currentThread().getName()+"卖票,ticket = "+this.ticket--);
}else{
System.out.printIn("票已经买完了");
break;
}
}
}
}
}
public class ThreadDemo{
public static void main(String[] args) throws Exception{
MyThread mt = new MyThread();
new Thread(mt,"票商A").start();
new Thread(mt,"票商B").start();
new Thread(mt,"票商C").start();
}
}
// 执行结果:不会出现票为-1的情况
5、使用同步方法解决问题:只需要在方法定义上使用synchronized关键字即可。
class MyThread implements Runnable{
private ticket =10; // 有10张票
// 同步方法,同步锁,一次只允许一个线程执行
public synchronized boolean sale(){
if(this.ticket > 0){
System.out.printIn(Thread.currentThread().getName()+"卖票,ticket = "+this.ticket--);
return true;
}else{
System.out.printIn("票已经买完了");
return false;
}
}
@Override
public void run(){
while(this.sale()){
;
}
}
}
public class ThreadDemo{
public static void main(String[] args) throws Exception{
MyThread mt = new MyThread();
new Thread(mt,"票商A").start();
new Thread(mt,"票商B").start();
new Thread(mt,"票商C").start();
}
}
// 执行结果:不会出现票为-1的情况
二、线程死锁
1、死锁指的是若干个线程彼此互相等待的状态。
2、造成死锁的主要原因是因为彼此都在互相等待着,等待着对方先让出资源。死锁是开发中出现的不确定状态,有的时候代码如果处理不当则会不定期出现死锁,这是属于正常开发中的调试问题。
范例:互不想让,一直等待
class PersonOne{
public synchronized void say(PersonTwo two){
System.out.printIn("我要筷子!");
}
public synchronized void get(){
System.out.printIn("我拿到筷子了!");
}
}
class PersonTwo{
public synchronized void say(PersonOne one){
System.out.printIn("我要勺子!");
}
public synchronized void get(){
System.out.printIn("我拿到勺子了!");
}
}
public class DeadLock implements Runnable{
PersonOne one = new PersonOne();
PersonTwo two = new PersonTwo();
@Override
pulic void run(){
one.say(two);
}
public DeadLock(){
new Thread(this).start();
two.say(one);
}
public void static main(String[] args){
new DeadLock();
}
}
// 执行结果:造成死锁,两个线程互不相让,一直等待
// 我要勺子
// 我要筷子
3、总结:若干个线程访问同一资源时一定要进行同步处理,而过多的同步会造成死锁。