6.11去面试,谈到多线程如何保证数据先后顺序
http://www.blogjava.net/tscfengkui/archive/2010/11/10/337709.html?opt=admin
锁住一个方法,
package com.dr.runnable2;
class TicketSouce implements Runnable
{
//票的总数
private int ticket=10;
public void run()
{
for(int i=1;i<50;i++)
{
try {
//休眠1s秒中,为了使效果更明显,否则可能出不了效果
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sale();
}
}
public synchronized void sale()
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket--+"号票");
}
}
}
public class Test {
public static void main(String args[])
{
TicketSouce mt=new TicketSouce();
//基于火车票创建三个窗口
new Thread(mt,"a").start();
new Thread(mt,"b").start();
new Thread(mt,"c").start();
}
}
锁住自身对象:
package com.dr.runnable2;
class TicketSouce implements Runnable
{
//票的总数
private int ticket=10;
public void run()
{
for(int i=1;i<50;i++)
{
synchronized(this){
if(ticket>0)
{
//休眠1s秒中,为了使效果更明显,否则可能出不了效果
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket--+"号票");
}
}
}
}
}
public class Test {
public static void main(String args[])
{
TicketSouce mt=new TicketSouce();
//基于火车票创建三个窗口
new Thread(mt,"a").start();
new Thread(mt,"b").start();
new Thread(mt,"c").start();
}
}
自己写了一个对象锁来测试
public class LockTest {
public static void main(String[] args) {
Object ob = new Object();
for (int i = 0; i < 20; i++) {
(new mThread(ob,"this is " + i)).start();
}
}
}
class mThread extends Thread {
private Object locker;
private String text;
public mThread (Object locker,String text) {
this.locker=locker;
this.text = text;
}
@Override
public void run() {
synchronized(locker) {
//休眠1s秒中,为了使效果更明显,否则可能出不了效果
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(text);
}
}
}
运行结果:
this is 0
this is 19
this is 18
this is 17
this is 16
this is 15
this is 14
this is 13
this is 12
this is 11
this is 10
this is 9
this is 8
this is 7
this is 6
this is 5
this is 4
this is 3
this is 2
this is 1
0先出现是因为0先进入了
后面的倒着拿到锁,顺序就这样出现了
这种方法虽然实现了锁,但是顺序乱了,所以锁住runable才是最佳的锁方案。