BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #13382同步于 2010/3/7
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

请教线程锁的问题

xgtandyx
2010/3/7镜像同步3 回复
小弟在做一个一个程序的时候,希望主程序执行到一定代码时,启动一个线程,并等待主程序的一个标识符变化时唤醒,进而执行之后的代码,程序代码如下: 出现的问题是系统提示我没有上锁,这是为什么呢?请教各位大牛··· public class TimerTest extends Activity implements Runnable{ int num=0; Thread read=new Thread(this); int[] timerlenth={5000,6000,2000,4000}; int[] number={1,2,3,4}; Handler handler; TimerTask task; ViewFlipper vf; Timer timer = new Timer(); /** Called when the activity is first created. */ public Handler createHandle() { Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: vf=(ViewFlipper)findViewById(R.id.ViewFlipper01); num=1; break; super.handleMessage(msg); } }; return handler; } public TimerTask createTimerTask(final int i,final Handler handler) { TimerTask task = new TimerTask(){ public void run() { Message message = new Message(); message.what = i; handler.sendMessage(message); } }; return task; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //timer.schedule(task, 5000); //for(int i=0;i<timerlenth.length;i++) //{ handler=createHandle(); task= createTimerTask(number[0], handler); timer.schedule(task,timerlenth[0]); try { Go(read,num); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //vf=(ViewFlipper)findViewById(R.id.ViewFlipper01); /**/ vf.startFlipping(); try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } vf.stopFlipping(); // } } @Override public void run() { // TODO Auto-generated method stub } public synchronized void Go(Thread a,int b) throws InterruptedException {//这个方法是设定线程锁的 while(b==0) { a.wait(); } vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_in1)); vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_out1)); num=0; notify(); } }
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
greedisgood机器人#1 · 2010/3/7
各线程要锁定同一个对象。 如果想要更详细的解释建议lz把代码全发上来。
fireflyk机器人#2 · 2010/3/7
【 在 greedisgood 的大作中提到: 】 : 各线程要锁定同一个对象。 : 如果想要更详细的解释建议lz把代码全发上来。 是因为不同对象吧?! 如果是static的函数就正常了吧?!
xgtandyx机器人#3 · 2010/3/7
谢谢两位啊,问题解决了