线程控制同步问题 [英] Thread synchonization issue

查看:565
本文介绍了线程控制同步问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我需要estalish与Web服务器的HTTP连接,HTTP连接建立时,用户选择一个ListField元素。它正常工作,我写了一个方法来建立HTTP连接,并将其返回结果和我的程序过程中使用这些数据。

但它挂起,因为我在一个单独的线程(我写来建立HTTP连接的方法是在一个单例类)写道不是方法的用户界面。现在,我改变我的方法,在一个单独的线程,现在我得到了非法线程状态异常。

所以我改变了我的班(HttpConnection的类现在它不是单例),现在也没有非法状态异常,但我希望我没有得到的结果。

我在Java和黑莓经验少,我不知道该怎么两个线程同步。所以我介绍一个静态变量'我'时,程序进入到它的线程变为0时,当它得到了HTTP响应把它改为1。

因此​​,在等待我的程序使用whil​​e循环,并检查了我的价值。当它变成1,我收到HTTP响应(这也是一个静态字符串变量)。但是,现在也是我的计划无限期挂起,我知道这是不是一个好方法。

请帮忙过度分享关于多线程控制同步你的想法来的问题,链接codeS等。

其运行我的方法:

 公共无效的run(){
    I = 0;
    observerStatusUpdate(我,请等待);
    的StreamConnection的StreamConnection = NULL;
    为InputStream的InputStream = NULL;
    的HttpConnection的HttpConnection = NULL;
    字符串结果=;
    尝试{
        的StreamConnection =(的StreamConnection)Connector.open(URL);
        的HttpConnection =(HttpConnection的)的StreamConnection;
        httpConnection.setRequestMethod(HttpConnection.GET);
        //httpConnection.setRequestProperty(\"Content-Type,// JSON);
        INT则httpStatus = httpConnection.getResponse code();
        如果(==则httpStatus HttpConnection.HTTP_OK){
            的InputStream = streamConnection.openInputStream();
            //字节[] = radioTimeData新的字节[8000];
            字节radioTimedataByte;
            而((radioTimedataByte =(字节)inputStream.read())!= - 1){
                结果=结果+(字符)radioTimedataByte;
            }            HTT preS =结果;
            的setResult(结果);
            I = 1;            observerStatusUpdate(ⅰ,);        }
    }赶上(IOException异常五){
        I = 1;
        UiApplication.getUiApplication()的invokeLater(Runnable的新(){            公共无效的run(){
                Dialog.alert(无Internet连接);
                //System.exit(0);
            }
        });
        的System.out.println(E);
    }

和它的使用另一个类像

称为

  grabAPIFactory.setUrl(NEWURL,01);
grabAPIFactory.start();
grabAPIFactory.setPriority(Thread.MAX_PRIORITY);
而(GrabapiFactory.i == 0){
    Thread.sleep()方法;
}
字符串HTT presult = GrabapiFactory.htt preS; //静态variale得到来自服务器的结果
//过程HTT presult这里.....


解决方案

从你的描述它听起来像你应该重新考虑你的应用程序架构。我相信那些sigletons /等待环路哈克/丑陋的方式做你所需要的。

基本上所有你需要知道的是:你需要做一个UI线程未便非UI线程被当,然后在BB一个常见的​​模式是使用下面的方法之一:

所以在用户事件(点击)开始一个新的这的确网络(或其他一些潜在的长期运行的操作),当你需要更新UI (如推/弹出一个屏幕,在字段更改外观),那么你使用应用.invokeLater(Runnable接口可运行)

另外,请查阅 BB用户界面概述和< A HREF =htt​​p://www.thinkingblackberry.com/archives/182相对=nofollow>黑莓UI线程 - 最基础

In my app I need to estalish an Http Connection with a web server, the http connection is established when user select a ListField element. It works properly, I wrote a method to establish http connection and it returns a result and my program process these data.

But it hangs the UI since the method I wrote not in a seperate thread (the method I wrote to establish http connection is in a singleton class). Now I change my method in a seperate thread, now I got illegal Thread State exception.

So I changed my class (HttpConnection class-now its not singleton),now there is no illegal state exception, but I don't get the result as I desired.

I have less experience in java and blackberry, I don't know how to synchronize two threads. So I introduce a static variable 'i' at when program enters to the thread it become 0 and when it got http response it changed to 1.

So in waits my program using a while loop and check the i value. When it become 1, I receive the http response (which is also a static string variable). But now also my program hangs indefinitely, I know this is not a good method.

Please help to over come the problem by sharing your ideas about thread synchonization, links codes etc.

its my run method:

public void run() {
    i =0;
    observerStatusUpdate(i, "Please Wait");
    StreamConnection streamConnection=null;
    InputStream inputStream=null;
    HttpConnection httpConnection = null;
    String result="";
    try {
        streamConnection=(StreamConnection)Connector.open(url);
        httpConnection=(HttpConnection)streamConnection;
        httpConnection.setRequestMethod(HttpConnection.GET);
        //httpConnection.setRequestProperty("Content-Type", "//json");
        int httpStatus=httpConnection.getResponseCode();
        if(httpStatus==HttpConnection.HTTP_OK){
            inputStream = streamConnection.openInputStream();
            //byte[] radioTimeData=new byte[8000];
            byte radioTimedataByte;                 
            while((radioTimedataByte=(byte)inputStream.read())!=-1){
                result=result+(char)radioTimedataByte;
            }

            httpres = result;   
            setResult(result);
            i=1;

            observerStatusUpdate(i, "");

        }
    } catch (IOException e) {   
        i=1;
        UiApplication.getUiApplication().invokeLater(new Runnable() {

            public void run() {
                Dialog.alert("No Internet Connectivity");   
                //System.exit(0);
            }
        });
        System.out.println(e);
    }

And its called using another class like

grabAPIFactory.setUrl(newUrl,o1);           
grabAPIFactory.start();
grabAPIFactory.setPriority(Thread.MAX_PRIORITY);
while(GrabapiFactory.i==0){
    Thread.sleep();
}
string httpresult = GrabapiFactory.httpres;// static variale getting result from server
// process the httpresult here.....

解决方案

From your description it sounds like you should reconsider your app architecture. I believe those sigletons/waiting loops are hacky/ugly ways to do what you need.

Basically all what you need to know is: when being on a non-UI thread you need to make smth on a UI-thread, then a common pattern on BB is to use one of the following methods:

So upon user event (a click) you start a new Thread which does networking (or some other potentially long-running actions) and when you need to update the UI (e.g. push/pop a Screen, change appearance on a Field) then you use Application.invokeLater(Runnable runnable).

Also check BB User Interface Overview and BlackBerry UI Threading - The Very Basics.

这篇关于线程控制同步问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆