Search Results

Search found 8588 results on 344 pages for 'thread abort'.

Page 20/344 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • MAKE CROSS THREAD METHOD CALLS USING INVOKE METHOD OF THE CONTROL

    Cross threading is a phenomina normally happening in any of application debug session. Developer may not able to understand what's this all about. He may not actually coded for any such scenario like Threading. But this exception may raise especially in side a method where you are accessing any of the GUI control menthod. One natural scenaio will happen, once you are handling with FielSystemWatcher class. But here 1st I will create a sceanrio and then will give you 2 way resolution too.

    Read the article

  • Error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException [migrated]

    - by user134212
    I'm new here. I'm learning how to program on java and I have a problem with my code. I really have no clue why my code is not working. I think my mistake may be here, but I'm not quite sure. m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); My Complete code import java.awt.*; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class Practica2 { private int opcion,ren2,col2; private JFrame ventana,ventanaPrintMatriz; private JPanel panel,panel2; private Border borderRed2,borderBlue2,borderGreen2,borderGreen4; private Color red,green,blue,white,black; private Font Verdana14,ArialBlack18; private JLabel labelTitulo; public JButton btSalir,btSumar,btRestar,btMultiplica,btTranspuesta,btCrear; private ImageIcon suma,resta,multi,crear,salir,trans; private boolean ventanaAbierta = false; private static ValidacionesMatrices valida; private static Operaciones operacion; private static Matriz m1,m2,m3; private static ImprimirMatriz printMat; public Practica2() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Operaciones con Matrices"); ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Sale del programa System.exit(0); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(150,150,300,380); //ventana.setBounds(0,0,650,650); } public void inicializarComponentes() { panel2 = new JPanel(); panel2.setLayout(null); labelTitulo = new JLabel("Practica #2"); suma = new ImageIcon("suma1.png"); resta = new ImageIcon("resta1.png"); multi = new ImageIcon("multi1.png"); trans = new ImageIcon("trans2.png"); crear = new ImageIcon("crear1.png"); salir = new ImageIcon("salir1.png"); btTranspuesta = new JButton("Transpuesta",trans); btMultiplica = new JButton("Multiplica",multi); btRestar = new JButton("Restar",resta); btSumar = new JButton("Sumar",suma); btCrear = new JButton("Crear",crear); btSalir = new JButton("Salir",salir); //Tipo de letra ArialBlack18 = new Font("Arial Black",Font.BOLD,18); //Color green = new Color(0,255,0); //Formato labelTitulo labelTitulo.setBounds(80,-60,200,150); labelTitulo.setFont(ArialBlack18); labelTitulo.setForeground(blue); labelTitulo.setVisible(true); //Formato de CrearMatriz btCrear.setBounds(80,50,130,30); btCrear.setToolTipText("Crea una matriz"); //Formato de Muliplica btMultiplica.setBounds(80,100,130,30); btMultiplica.setToolTipText("Mat[A] * Mat[B]"); //Formato de botonRestar btRestar.setBounds(80,150,130,30); btRestar.setToolTipText("Mat[A] - Mat[B]"); //Formato del botonSumar btSumar.setBounds(80,200,130,30); btSumar.setToolTipText("Mat[A] + Mat[B]"); //Formato de Transpuesta btTranspuesta.setBounds(80,250,130,30); btTranspuesta.setToolTipText("Mat[A]^-1"); //Formato del botonSalir btSalir.setBounds(80,300,130,30); //Agregando componentes al panel1 panel2.add(labelTitulo); panel2.add(btMultiplica); panel2.add(btCrear); panel2.add(btRestar); panel2.add(btSumar); panel2.add(btSalir); panel2.add(btTranspuesta); //Formato panel2 panel2.setBackground(green); panel2.setVisible(true); panel2.setBounds(0,0,300,380); //Argregamos componentes al panelPrincipal= panel.add(panel2); //BotonCrear btCrear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) //throws IOException { if(ventanaAbierta==false) { ventanaAbierta=true; new CrearMatriz(); } else { JOptionPane.showMessageDialog(null,"Ya se crearon las Matrices"); } } }); m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); //BotonSalir btSalir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); panel.setVisible(true); panel.setBounds(0,0,350,380); } class VentanaMatriz { private JFrame ventana; private JPanel panel; private JTextArea textArea1,textArea2; private JLabel mat1,mat2; private JTextField textField1; public VentanaMatriz() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Creacion de Matrices"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { ventana.dispose(); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(200,100,850,420); } public void inicializarComponentes() { //Colores black = new Color(0,0,0); white = new Color(255,255,255); blue = new Color(0,0,255); green = new Color(0,255,0); red = new Color(255,0,0); //Tipo de letra Verdana14 = new Font("Verdana",Font.BOLD,14); //Tipos de borde borderRed2 = BorderFactory.createLineBorder(red,2); borderBlue2 = BorderFactory.createLineBorder(blue,2); borderGreen2 = BorderFactory.createLineBorder(green,2); borderGreen4 = BorderFactory.createLineBorder(green,4); //Agregando componentes al panel1 panel.add(mat1); panel.add(textArea1); panel.add(mat2); panel.add(textArea2); //Formato panel2 panel.setBackground(blue); panel.setVisible(true); panel.setBounds(0,0,850,420); } } class CrearMatriz { public int col1,re1,ren2,col2; public Matriz m1,m2,m3; public CrearMatriz() { int col1,ren1,ren2,col2; ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz A: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz A: ")); final Matriz m1= new Matriz(ren2,col2); ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz B: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz B: ")); final Matriz m2= new Matriz(ren2,col2); m3 = new Matriz(ren2,col2); m1.llenarMatriz(); m2.llenarMatriz(); m1.printMat(); m2.printMat(); } public void SUMA(Matriz m1,Matriz m2) { Matriz m3; if(ventanaAbierta==false) { m3 = new Matriz(ren2,col2); if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } } } public void RESTA() { } //btSumar = new JButton("Sumar",suma); //BotonSumar //Mostrar matriz 1 y 2 // System.out.println("\n\n\nMatriz 1="); // m1.imprimeMatriz(); // System.out.println("\nMatriz 2="); //Poner en botones /* if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } if(valida.validaSumayResta(m1,m2)) { m3=operacion.restaMat(m1,m2); JOptionPane.showMessageDialog(null,"La resta es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la resta"); } if(valida.validaMultiplicacion(m1,m2)){ m3=operacion.multiplicaMat(m1,m2); JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la multiplicacion"); } JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m1=operacion.transpuesta(m1); m2=operacion.transpuesta(m2); */ } class Matriz { public JTextField matriz; //public JTextArea texto; private JFrame ventanaPrintMatriz; private JPanel panel2; int ren; int col; int pos[][]; public Matriz(int ren1, int col1) { ren = ren1; col = col1; pos = new int [ren][col];/*una matriz de enteros de renglon por columan*/ } public void llenarMatriz() { for(int i=0;i<ren;i++) for(int j=0;j<col;j++) pos[i][j]=(int) (Math.random()*10);/*la posicion i y j crea un entero random*/ } /*vuelve a recorrer los espacio de i y j*/ } //Esta clase era un metodo de CrearMatriz class ImprimirMatriz { public void ImprimirMatriz() { panel2 = new JPanel(); panel2.setLayout(null); ventanaPrintMatriz = new JFrame("Matriz"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Practica2.ventanaAbierta=false; ventana.dispose(); } }); int i,j; int x=0,y=0; borderRed2 = BorderFactory.createLineBorder(red,2); white = new Color(255,255,255); red = new Color(255,0,0); black = new Color(0,0,0); blue = new Color(0,0,255); for(i=0;i<ren;i++) { for(j=0;j<col;j++) { matriz = new JTextField(" "+pos[i][j]); matriz.setBorder(borderRed2); matriz.setForeground(white); matriz.setBounds(x+25,y+25,25,25); matriz.setBackground(black); matriz.setEditable(false); matriz.setVisible(true); //Se incrementa la coordenada en X //para el siguiente Textfield no se encime x=x+35; //Agregamos el textField al panel panel2.add(matriz); } //Regreso las cordenadas de X a 0 para que el //siguiente renglon empieze en donde mismo x=0; //Incremento las coordenada Y para que se brinque //de linea y=y+35; } //Formato panel2 panel2.setBounds(150,150,350,380); panel2.setBackground(blue); //panel2.setEditable(false); panel2.setVisible(true); //Formato de Ventana ventanaPrintMatriz.setContentPane(panel2); ventanaPrintMatriz.setBounds(150,150,350,380); ventanaPrintMatriz.setResizable(false); ventanaPrintMatriz.setVisible(true); } } class Operaciones { public Matriz sumaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]+m2.pos[i][j]; return m3; } public Matriz restaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]-m2.pos[i][j]; return m3; } public Matriz multiplicaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m2.col); for(int i=0;i<m1.ren;i++) for(int j=0;j<m2.col;j++) { m3.pos[i][j]=0; for(int k=0;k<m1.col;k++) m3.pos[i][j]+=(m1.pos[i][k]*m2.pos[k][j]); } return m3; } public Matriz transpuesta(Matriz m1) { Matriz m3=new Matriz(m1.col,m1.ren); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[j][i]; return m3; } } class ValidacionesMatrices { public boolean validaSumayResta(Matriz m1, Matriz m2) { if((m1.ren==m2.ren) && (m1.col==m2.col)) return true; else return false; } public boolean validaMultiplicacion(Matriz m1, Matriz m2) { if(((m1.ren==m2.ren) && (m1.col==m2.col)) || (m1.col==m2.ren)) return true; else return false; } } public static void main(String[] args) { Practica2 practica2 = new Practica2(); practica2.inicializarComponentes(); } } Exc

    Read the article

  • google maps based desktop application

    - by dramaticlook
    I want to build a desktop application which has google maps embedded to it. This app should have a thread to read coordinate data online a usb microphone to use. This application will move the google map markers to their new locations based on the data retrieved from online connections on each refresh. As far as I know gmaps has a javascript API so the first idea in my mind was to embed this mapview into a java applet. So the application will run on a browser. Im not sure if this will work. Do you guys have any idea about this or any other advices you might have? Thanks in advance!!!

    Read the article

  • Thread count in Java game

    - by Taylor Hill
    I'm just curious as to what a reasonable number of threads is for a simple 2D mmo in Java. Is it reasonable to have two threads per connection, one for the input stream and one for the output stream? The reason I ask is because I use a blocking method on the input stream, and a workaround seems unnecessarily complex if I were to try to get around it without adding threads. This is mostly for my own edification; I don't expect to have 5 million people playing it ever, or even 5, but I'm wondering what a good scalable solution is, and if this is reasonable for a small server (<30 connections).

    Read the article

  • Thread locking issue with FileHelpers between calling engine.ReadNext() method and readign engine.Li

    - by Rad
    I use producer/consumer pattern with FileHelpers library to import data from one file (which can be huge) using multiple threads. Each thread is supposed to import a chunk of that file and I would like to use LineNumber property of the FileHelperAsyncEngine instance that is reading the file as primary key for imported rows. FileHelperAsyncEngine internally has an IEnumerator IEnumerable.GetEnumerator(); which is iterated over using engine.ReadNext() method. That internally sets LineNumber property (which seems is not thread safe). Consumers will have Producers assiciated with them that will supply DataTables to Consumers which will consume them via SqlBulkLoad class which will use IDataReader implementation which will iterate over a collection of DataTables which are internal to a Consumer instance. Each instance of will have one SqlBulkCopy instance associate with it. I have thread locking issue. Below is how I create multiple Producer threads. I start each thread afterwords. Produce method on a producer instance will be called determining which chunk of input file will be processed. It seems that engine.LineNumber is not thread safe and I doesn't import a proper LineNumber in the database. It seems that by the time engine.LineNumber is read some other thread called engine.ReadNext() and changed engine.LineNumber property. I don't want to lock the loop that is supposed to process a chunk of input file because I loose parallelism. How to reorganize the code to solve this threading issue? Thanks Rad for (int i = 0; i < numberOfProducerThreads; i++) DataConsumer consumer = dataConsumers[i]; //create a new producer DataProducer producer = new DataProducer(); //consumer has already being created consumer.Subscribe(producer); FileHelperAsyncEngine orderDetailEngine = new FileHelperAsyncEngine(recordType); orderDetailEngine.Options.RecordCondition.Condition = RecordCondition.ExcludeIfBegins; orderDetailEngine.Options.RecordCondition.Selector = STR_ORDR; int skipLines = i * numberOfBufferTablesToProcess * DataBuffer.MaxBufferRowCount; Thread newThread = new Thread(() => { producer.Produce(consumer, inputFilePath, lineNumberFieldName, dict, orderDetailEngine, skipLines, numberOfBufferTablesToProcess); consumer.SetEndOfData(producer); }); producerThreads.Add(newThread); thread.Start();} public void Produce(DataConsumer consumer, string inputFilePath, string lineNumberFieldName, Dictionary<string, object> dict, FileHelperAsyncEngine engine, int skipLines, int numberOfBufferTablesToProcess) { lock (this) { engine.Options.IgnoreFirstLines = skipLines; engine.BeginReadFile(inputFilePath); } int rowCount = 1; DataTable buffer = consumer.BufferDataTable; while (engine.ReadNext() != null) { lock (this) { dict[lineNumberFieldName] = engine.LineNumber; buffer.Rows.Add(ObjectFieldsDataRowMapper.MapObjectFieldsToDataRow(engine.LastRecord, dict, buffer)); if (rowCount % DataBuffer.MaxBufferRowCount == 0) { consumer.AddBufferDataTable(buffer); buffer = consumer.BufferDataTable; } if (rowCount % (numberOfBufferTablesToProcess * DataBuffer.MaxBufferRowCount) == 0) { break; } rowCount++; } } if (buffer.Rows.Count > 0) { consumer.AddBufferDataTable(buffer); } engine.Close(); }

    Read the article

  • Boost Thread Hanging on _endthreadex

    - by FranticPedantic
    I think I am making a simple mistake, but since I noticed there are many boost experts here, I thought I would ask for help. I am trying to use boost threads(1_40) on windows xp. The main program loads a dll, starts the thread like so (note this is not in a class, the static does not mean static to a class but private to the file). static boost::thread network_thread; network_start() { // do network stuff until quit is signaled } DllClass::InitInstance() { network_thread = boost::thread(boost::bind<void>(network_start)); } DllClass::ExitInstance() { //signal quit (which works) //the following code is slightly verbose because I'm trying to figure out what's wrong try { if (network_thread.joinable() ) { network_thread.join(); } else { TRACE("Too late!"); } } catch (boost::thread_interrupted&) { TRACE("NET INTERRUPTED"); } } The problem is that the main thread is hanging on the join, and the network thread is hanging at the end of _endthreadex. What am I misunderstanding?

    Read the article

  • call setListAdapter() from inside a thread

    - by Mats Hofman
    Hi, I have a problem with my ListActivity, i use a thread to show a ProgressDialog where get a list of all installed applications. I turn it into a list adapter and than i want to set the listadapter of the activity but i can't do that from the thread. I get the following error: ERROR/AndroidRuntime(14429): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. new Thread() { public void run() { showList(); // the method where i get all the apps and have the setListAdapter(); method progressDialog.dismiss(); } }.start(); How do I get it so I can use the setListAdapter from inside my thread

    Read the article

  • Instantiating a System.Threading.Thread object in Jscript

    - by user297029
    I'm trying to create a new System.Threading.Thread object using Jscript, but I can't get the constructor to work. If I just do the following, var thread = new Thread( threadFunc ); function threadFunc() { // do stuff } then I get error JS1184: More than one constructor matches this argument list. However, if I try to coerce threadFunc to System.Threading.ThreadStart via var thread = new Thread( ThreadStart(threadFunc) ) I get error JS1208: The specified conversion or coercion is not possible Anyone know how to do this? It seems like it should be trivial.

    Read the article

  • Android Cannot execute setListAdapter() user thread.

    - by Ameya
    I got a class class MyClass extends ListActivity implements Runnable{ ArrayList array; onCreate(){ Thread thread = new Thread(this); hread.start(); } @Overriding void run(){ addAnElement(); } void addAnElement(){ if(null==array) array=new ArrayList(); array.add("Some junck string"); this.setListAdapter(.....,array); } } on executing in emulator get error ERROR/AndroidRuntime(288): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. I know we cannot access UI calls from user thread. Can anyone help.

    Read the article

  • Boost::Thread or fork() : Multithreaded HTTP Proxy

    - by osmano807
    I'm testing boost::thread on a system. It happens that I needed to act as a fork(), because one thread modifies the other variables, even member variables of class I do the project using fork() or is there some alternative still using boost::thread? Basically I run this program in Linux and maybe FreeBSD. It is an http proxy,accept() in main thread, and a function that accepts a class (where there is the file descriptor socket) in a secondary thread that makes the service. Is there a better way to implement a proxy?

    Read the article

  • Why is thread local storage so slow?

    - by dsimcha
    I'm working on a custom mark-release style memory allocator for the D programming language that works by allocating from thread-local regions. It seems that the thread local storage bottleneck is causing a huge (~50%) slowdown in allocating memory from these regions compared to an otherwise identical single threaded version of the code, even after designing my code to have only one TLS lookup per allocation/deallocation. This is based on allocating/freeing memory a large number of times in a loop, and I'm trying to figure out if it's an artifact of my benchmarking method. My understanding is that thread local storage should basically just involve accessing something through an extra layer of indirection, similar to accessing a variable via a pointer. Is this incorrect? How much overhead does thread-local storage typically have? Note: Although I mention D, I'm also interested in general answers that aren't specific to D, since D's implementation of thread-local storage will likely improve if it is slower than the best implementations.

    Read the article

  • C# - Which is more efficient and thread safe? static or instant classes?

    - by Soni Ali
    Consider the following two scenarios: //Data Contract public class MyValue { } Scenario 1: Using a static helper class. public class Broker { private string[] _userRoles; public Broker(string[] userRoles) { this._userRoles = userRoles; } public MyValue[] GetValues() { return BrokerHelper.GetValues(this._userRoles); } } static class BrokerHelper { static Dictionary<string, MyValue> _values = new Dictionary<string, MyValue>(); public static MyValue[] GetValues(string[] rolesAllowed) { return FilterForRoles(_values, rolesAllowed); } } Scenario 2: Using an instance class. public class Broker { private BrokerService _service; public Broker(params string[] userRoles) { this._service = new BrokerService(userRoles); } public MyValue[] GetValues() { return _service.GetValues(); } } class BrokerService { private Dictionary<string, MyValue> _values; private string[] _userRoles; public BrokerService(string[] userRoles) { this._userRoles = userRoles; this._values = new Dictionary<string, MyValue>(); } public MyValue[] GetValues() { return FilterForRoles(_values, _userRoles); } } Which of the [Broker] scenarios will scale best if used in a web environment with about 100 different roles and over a thousand users. NOTE: Feel free to sugest any alternative approach.

    Read the article

  • Fast single thread comet server, possible?

    - by Pepijn
    I recently encountered a few cases where a server would distribute an event stream that contains the exact same data for all listeners, such as a 'recent activity' box. It occurred to me that it is quite strange and inefficient to have a server like Apache run a thread processing and querying the database for every single comet stream containing the same data. What I would do for those global(not per user) streams is run a single thread that continuously emits data, and a new (green)thread for every new request that outputs the headers and then 'merges' into the main thread. Is it possible for one thread to serve multiple sockets, or for multiple clients to listen to the same socket? An example o = event # threads received | a b # 3 o / / # 3 - |/_/ | # 1 o c # 2 a, b | / o/ # 2 a, b o # 1 a, b, c | # connection b closed o # 1 a, c Does something like this exist? Would it work? Is it possible to do? Disclaimer: I'm not a server expert.

    Read the article

  • Which thread invokes SensorEventListener.onSensorChanged

    - by Christoph Heindl
    From my records it seems that SensorEventListener.onSensorChanged callback is called by the same thread that registered the callback. I.e there must be some message-queue synchronization going on in the background which allows the activitys UI-Thread to handle the callbacks. That leads to my question: Is there a need to synchronize SensorEventListener.onSensorChanged with the activitys UI-thread, assuming that the activitys UI-thread registered the SensorEventListener? I cannot find any documentation references, but can see various examples calling invalidate() unsychronized or synchronize the entire callback. I used something along the lines of Log.i(TAG, "" + Thread.currentThread().getId()); to retrieve threading information. I'm running android 2.1 update1. Best regards, Christoph

    Read the article

  • Advantage of using Thread.Start vs QueueUserWorkItem

    - by Cheeso
    In multithreaded .NET programming, what are the decision criteria for using ThreadPool.QueueUserWorkItem versus starting my own thread via new Thread() and Thread.Start()? In a server app (let's say, an ASP.NET app or a WCF service) I think the ThreadPool is always there and available. What about in a client app, like a WinForms or WPF app? Is there a cost to spin up the thread pool? If I just want 3 or 4 threads to work for a short period on some computation, is it better to QUWI or to Thread.Start().

    Read the article

  • Sockets, Threads and Services in android, how to make them work together ?

    - by Spredzy
    Hi all, I am facing a probleme with threads and sockets I cant figure it out, if someone can help me please i would really appreciate. There are the facts : I have a service class NetworkService, inside this class I have a Socket attribute. I would like it be at the state of connected for the whole lifecycle of the service. To connect the socket I do it in a thread, so if the server has to timeout, it would not block my UI thread. Problem is, into the thread where I connect my socket everything is fine, it is connected and I can talk to my server, once this thread is over and I try to reuse the socket, in another thread, I have the error message Socket is not connected. Questions are : - Is the socket automatically disconnected at the end of the thread? - Is their anyway we can pass back a value from a called thread to the caller ? Thanks a lot, Here is my code public class NetworkService extends Service { private Socket mSocket = new Socket(); private void _connectSocket(String addr, int port) { Runnable connect = new connectSocket(this.mSocket, addr, port); new Thread(connect).start(); } private void _authentification() { Runnable auth = new authentification(); new Thread(auth).start(); } private INetwork.Stub mBinder = new INetwork.Stub() { @Override public int doConnect(String addr, int port) throws RemoteException { _connectSocket(addr, port); _authentification(); return 0; } }; class connectSocket implements Runnable { String addrSocket; int portSocket; int TIMEOUT=5000; public connectSocket(String addr, int port) { addrSocket = addr; portSocket = port; } @Override public void run() { SocketAddress socketAddress = new InetSocketAddress(addrSocket, portSocket); try { mSocket.connect(socketAddress, TIMEOUT); PrintWriter out = new PrintWriter(mSocket.getOutputStream(), true); out.println("test42"); Log.i("connectSocket()", "Connection Succesful"); } catch (IOException e) { Log.e("connectSocket()", e.getMessage()); e.printStackTrace(); } } } class authentification implements Runnable { private String constructFirstConnectQuery() { String query = "toto"; return query; } @Override public void run() { BufferedReader in; PrintWriter out; String line = ""; try { in = new BufferedReader(new InputStreamReader(mSocket.getInputStream())); out = new PrintWriter(mSocket.getOutputStream(), true); out.println(constructFirstConnectQuery()); while (mSocket.isConnected()) { line = in.readLine(); Log.e("LINE", "[Current]- " + line); } } catch (IOException e) {e.printStackTrace();} } }

    Read the article

  • java: relationship of the Runnable and Thread interfaces

    - by Karl Patrick
    I realize that the method run() must be declared because its declared in the Runnable interface. But my question comes when this class runs how is the Thread object allowed if there is no import call to a particular package? how does runnable know anything about Thread or its methods? does the Runnable interface extend the Thread class? Obviously I don't understand interfaces very well. thanks in advance. class PrimeFinder implements Runnable{ public long target; public long prime; public boolean finished = false; public Thread runner; PrimeFinder(long inTarget){ target = inTarget; if(runner == null){ runner = new Thread(this); runner.start() } } public void run(){ } }

    Read the article

  • Date Range Problem

    - by ungalnanban
    I have a log file which has first few characters of every line as a timestamp. 2010-06-01 04:56:02,802 DEBUG {Thread-27} Some text message 2010-06-01 04:56:02,802 DEBUG {Thread-27} Some text message 2010-06-01 04:56:02,802 DEBUG {Thread-27} Some text message 2010-06-01 04:56:02,802 DEBUG {Thread-27} Some text message 2010-06-01 05:22:02,802 DEBUG {Thread-27} Some text message 2010-06-01 05:22:02,802 DEBUG {Thread-27} Some text message 2010-06-01 05:22:02,802 DEBUG {Thread-27} Some text message 2010-06-01 05:22:02,802 DEBUG {Thread-27} Some text message 2010-06-01 06:43:02,802 INFO {Thread-27} Some text message 2010-06-01 06:43:02,803 INFO {Thread-27} Some text message 2010-06-01 06:43:02,804 INFO {Thread-27} Some text message 2010-06-01 06:43:02,804 INFO {Thread-27} Some text message 2010-06-01 06:43:02,809 DEBUG {Thread-27} Some text message 2010-06-01 06:43:02,809 DEBUG {Thread-27} Some text message 2010-06-01 06:43:02,809 DEBUG {Thread-27} Some text message 2010-06-01 07:08:02,809 DEBUG {Thread-27} Some text message 2010-06-01 07:08:02,809 DEBUG {Thread-27} Some text message My aim to find all such lines which have the timestamp of 1 hr before the current time. How can this be achieved?

    Read the article

  • python: can't terminate a thread hung in socket.recvfrom() call

    - by Dihlofos
    Hello, everyone I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing: from socket import * from threading import Thread from sys import exit class TestThread(Thread): def __init__(self,host="localhost",port=9999): self.sock = socket(AF_INET,SOCK_DGRAM) self.sock.bind((host,port)) super(TestThread,self).__init__() def run(self): while True: try: recv_data,addr = self.sock.recvfrom(1024) except (KeyboardInterrupt, SystemExit): sys.exit() if __name__ == "__main__": server_thread = TestThread() server_thread.start() while True: pass The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom(). Please, help me resolve this.

    Read the article

  • Thread.sleep vs Monitor.Wait vs RegisteredWaitHandle?

    - by Royi Namir
    (the following items has different goals , but im interesting knowing how they "PAUSEd") questions Thread.sleep - Does it impact performance on a system ?does it tie up a thread with its wait ? what about Monitor.Wait ? what is the difference in the way they "wait"? do they tie up a thread with their wait ? what aboutRegisteredWaitHandle ? This method accepts a delegate that is executed when a wait handle is signaled. While it’s waiting, it doesn’t tie up a thread. so some thread are paused and can be woken by a delegate , while others just wait ? spin ? can someone please make things clearer ? edit http://www.albahari.com/threading/part2.aspx

    Read the article

  • Secondary thread causes startup delay

    - by JK
    In my didFinishLaunchingWithOptions method I spawn a thread to perform some maintenance on my core data store. However, this increases the startup time by half a second. The startup view is a tableview which draws its content from the same store. If I let the thread sleep for a second, the startup time improves drastically. I would like to understand why the second thread is blocking/delaying the main thread. Is it because both are trying to access the store (The second thread has its own store coordinator and context) or another reason (e.g. dont spawn threads in didFinishLaunching)?

    Read the article

  • Thread-safe blocking queue implementation on .NET

    - by Shrike
    Hello. I'm looking for an implementation of thread-safe blocking queue for .NET. By "thread-safe blocking queue" I mean: - thread-safe access to a queue where Dequeue method call blocks a thread untill other thread puts (Enqueue) some value. By the moment I'v found this one: http://www.eggheadcafe.com/articles/20060414.asp (But it's for .NET 1.1). Could someone comment/criticize correctness of this implementation. Or suggest some another one. Thanks in advance.

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >