java之学习多线程(四)

来源:互联网 发布:淘宝c店运营 编辑:程序博客网 时间:2024/04/28 03:24

线程的同步与死锁

public class lock_line {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMyThread3 Me = new MyThread3();new Thread(Me ,"one").start();    new Thread(Me ,"three").start();    new Thread(Me,"two").start();}}class MyThread3 implements Runnable{int ticket1 = 6;@Overridepublic void run(){for(int x = 0;x < 10;x++){if(this.ticket1 > 0){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+"卖票,ticket="+ this.ticket1--);}}}}
结果

one卖票,ticket=6
three卖票,ticket=5
two卖票,ticket=4
one卖票,ticket=3
three卖票,ticket=2
two卖票,ticket=1
one卖票,ticket=0
three卖票,ticket=-1
出现负数,说明在同一个时间段内有多个线程在运作,修改了ticket,使票数不为零的判断之后的ticket变为负数。

解决的方法就是:同步,是多个操作在同一个时间里只能有一个线程进行,其他线程要等待此线程完成后才可以继续执行。

方法一:同步代码块( synchronized(同步对象){同步代码})

public class lock_line {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMyThread3 Me = new MyThread3();new Thread(Me ,"one").start();    new Thread(Me ,"three").start();    new Thread(Me,"two").start();}}class MyThread3 implements Runnable{int ticket1 = 6;@Overridepublic void run(){for(int x = 0;x < 10;x++){synchronized(this){if(this.ticket1 > 0){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+"卖票,ticket="+ this.ticket1--);}}}}}

方法二:同步方法

public class lock_line {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMyThread3 Me = new MyThread3();new Thread(Me ,"one").start();    new Thread(Me ,"three").start();    new Thread(Me,"two").start();}}class MyThread3 implements Runnable{int ticket1 = 6;@Overridepublic void run(){for(int x = 0;x < 10;x++){this.test();}}public synchronized void test(){if(this.ticket1 > 0){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+"卖票,ticket="+ this.ticket1--);}}}

在此处说明一个问题,加入同步后程序会变慢许多,所以代码性能会减低,但数据安全性会很高。

多线程访问同一资源时一定要考虑到同步的问题,过多的同步会带来死锁。

0 0
原创粉丝点击