Tengo 4 threads y dos se refieren a un objeto pero al hacer a un thread.sleep(x) no ejecuta ese thread para ambos objetos

Cree una ConcurrentLinkedQueue de strings, tengo dos colas y voy almacenando siempre datos (bucle en mi thread), luego por cada determinado tiempo una cola saca datos (bucle en thread) y luego la otra deberia tambien, pero ambas instrucciones de ambos threads se hacen al mismo tiempo, cuando necesito que por un tiempo se ejecute un thread y luego otro

``Entrada entrada_cola1 = new Entrada(cola1);     Salida salida_cola1 = new Salida(cola1);     Entrada entrada_cola2 = new Entrada(cola2);     Salida salida_cola2 = new Salida(cola2);      System.out.println("------------------------");     System.out.println("INICIO DE SIMULACION");     System.out.println("------------------------");     entrada_cola1.start();     entrada_cola2.start();     salida_cola1.start();     salida_cola2.start();     while(true){         try{         salida_cola2.sleep(rojo);         } catch(Exception e){         }         System.out.println("--------------------------------------------------------------------------------------------------------------");         System.out.println("SEMAFORO CAMBIO COLOR: ROJO-VERDE PARA COLA A: Se encuentran "+cola1.size()+ " Carros en cola A");         System.out.println("SEMAFORO CAMBIO COLOR: VERDE-AMARILLO-ROJO PARA COLA B: "+cola2.size()+" Carros en cola B");         System.out.println("---------------------------------------------------------------------------------------------------------------");           try{         salida_cola1.sleep(rojo);         }catch(Exception e){         }         System.out.println("----------------------------------------------------------------------------------------------------------------");         System.out.println("SEMAFORO CAMBIO COLOR: VERDE-AMARILLO-ROJO PARA COLA A: "+cola1.size()+" Carros en cola A");         System.out.println("SEMAFORO CAMBIO COLOR: ROJO-VERDE PARA COLA B: "+cola2.size()+" Carros en cola B");         System.out.println("-----------------------------------------------------------------------------------------------------------------");          } ``

El script basicámente coge los proxies que proporciona una web y los guarda en un txt. El caso es que quiero implementar el modulo threading ya que es muy lento,pero no lo consigo. (He investigado,he hecho script con Threads pero no consigo implementarlo en mi código) La idea sería que cada hilo ejecutase la función “check” con su proxie correspondiente,por ejemplo,de 10 en 10. Mi código:

``from colorama import Fore,Back,Style import requests import json import os import datetime  def check():     count = 0     os.system("cls")     today = datetime.datetime.today()     hoy = (f"{today.day}-{today.month}-{today.year}___{today.hour}-{today.minute}")     print (hoy)     nombre = (hoy+".txt")     good = open(nombre,"a+")     fichero = open("proxygen.txt","r+")     print (Back.BLACK+"TEST")     for ip_port in fichero:         todo = ip_port.split(":")         ip, port = ip_port.rstrip().split(":")         line = f'http://{ip}:{port}'         proxies = {'http': line, 'https': line}         try:             testIP = requests.get('https://httpbin.org/ip', proxies=proxies, timeout=3)             resIP = testIP.json()["origin"]             origin = resIP.split(",")[0]             if origin == ip:                 print(f"Proxy {ip}:{port}"+Fore.GREEN+"    OK"+Fore.WHITE)                 good.write(ip+"\n")                 count += 1              else:                 print(f"Proxy {ip}:{port}"+Fore.RED+"   BAD"+Fore.WHITE)            except:             print (f"Proxy {ip}:{port}"+Fore.RED+"    ERROR"+Fore.WHITE)     fichero.close()     good.close()     print (count)     check()     ``

Se que aquí no dan las cosas hechas pero solo pido que me ayudeis a encontrar el camino correcto.Saludos y gracias.

Com qual lib desenvolvo minha interface gráfica nesse projeto com aplicação de sockets e pool de threads em JAVA?

Então estou emperrado em meu projeto da faculdade (JAVA) programo à pouco tempo e não sei oq utilizar… tentei usar o javaFX pra fazer toda interface gráfica mas não consegui por não conseguir achar bons materiais na net, apenas aplicações para projetos simples de “Hello world” ou coisas do tipo que não me ajudam muito na hora da implementação de um projeto um pouco mais complexo. Como o professor exigiu apenas java (não autorizou usar Spring ou nenhuma outra framework, o que facilitaria muito a minha vida, mas enfim…).

Se alguém puder contribuir com dicas na estrutura do projeto e (principalmente) enviando bons materiais que possam me ajudar a decidir uma boa biblioteca pra desenvolver o front da aplicação agradeceria muito!

Let’s say I was working on a Swing application. Most of it is run on the EDT using `SwingUtilities.invokeLater()` inside the `main` method, because I heard (please correct me if I’m wrong) that that’s what you need to do with Swing.

However, some parts of it shouldn’t run on the EDT. These parts are parts that take long to complete (I assume that this is because long tasks on the EDT will interfere with GUI stuff the EDT should be doing, and thus these kinds of tasks should be run on parallel, on a different thread. Is this assumption correct?)

To do this, when I need to perform a task that takes long to complete and thus can’t be run on the EDT like the rest of the program, I create a new thread and run that task inside it.

My question is: When the `run()` method of that new thread finishes, aka the thread finished it’s job. Does it delete itself? Or does it keep existing in the memory?

Use hardware threads as independent cpus changes Barrier() behaviour

I am using Open MPI and C++ to try out simple programs on my laptop. When I use the 2 cores on my computer as processors, the program runs us expected. However, when I instead do –use-hwthread-cpus, it seams that I never get past the Barrier(). That is the only thing I am changing, just the way I start the program. It is the same .exe file running.

How to let a matlab mex function file create threads which keep on living in between function calls?

I have found out that statically allocated memory in mex files seems to survive between different calls from Matlab (unless the user types “clear mex” or “clear all”). Even if they didn’t, there do exist functions which let you mark stuff as persistent in memory.

Now to the question of mine: I am aware that some OS:es cough can take considerable time to start and stop threads. Would there be some way to let threads live on after a mex function call and be taken right back up at the next call.

The obvious goal would be to gain speed so any answer which gives some other kind of hint how to do this would be acceptable to me too.

Does Akka support communication with external threads

I have been developing with Orleans actor implementation. Recently, I saw that we were scheduling a long running job on an actor, which was effectively blocking the actor since it couldn’t process the next messages in its mailbox. Fortunately, Orleans provides a solution where a long running task can be scheduled on an external .Net thread and the actor is free to process next messages in the mailbox. Orleans also provides a way for the external .Net thread to send messages to actors. So, after the job was finished, we made the external .Net thread send required messages.

We were viewing this capability of Orleans as an actor being multithreaded. However, the actor model considers actors to be single threaded. Therefore, we were thinking about whether this multithreaded view of actors violates the actor model rules. When we asked this question on the Orleans forum, the response was `it is much better to view external tasks/threads, external services, etc. as external resources with side effects outside of the actor. Actors can call them and they can call actors, but that doesn't make these external resources part of the actor`.

Akka is another major implementation of actor model. Hence, I have following questions: –

1. Does Akka have any similar feature like Orleans where a long running task can be given to a separate thread while the actor proceeds onto the next message? I found something similar for Akka here, which is further explained here. These links talk about multiple threads in Akka, but I am not sure.
2. Does the `existence of external resources that can communicate with actors` or `actor with multiple threads` violate the principles of the actor model?

Multithreaded parameterized programs with superexponential shared memory size in the number of threads?

In this question, a program means a parameterized multithreaded program with the interleaving semantics, a finite number of per-thread states (which may depend on the number of threads), and finite number of shared states (which may depend on the number of threads).

A shared state is a valuation of the shared memory, and a per-thread (in other terminology, local) state is the valuation of thread-local memory (we assume no stack). Interleaving semantics means that the actions of the threads are interleaved on a single processor and a thread has rw-access to the shared memory and its own local memory and no access to the local memories of the other threads. Parameterized means that we conside a family of programs generated from a finite-desciption template such that the $$n$$th member of the family has $$n$$ threads (which typically coincide up to the thread identifier).

To the best of my knowledge, for such a program, the size of the shared state-space is anywhere between constant (e.g., for a single boolean lock variable) and exponential (e.g., Peterson mutual exclusion protocol) in the number of the threads $$n$$.

Is there any well-known academic program in which the size of the shared state-space grows superexponentially in $$n$$?

Problema com dois metodos e threads no java

Bom ao debugar meu codigo acabei descobrindo que estou com problemas nessas duas linhas de um metodo:

``    String sql = "SELECT login,senha FROM usuario where login = '" + jLogin.getText() + "' and  senha = '" + jSenha.getText() + "'";     conn.executeSQL(sql); ``

ou possívelmente problema no metodo executeSQL

``public void executeSQL(String sql) {     try {         statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);         resultset = statement.executeQuery(sql);     } catch (SQLException sqlex) {         System.out.println("Não foi possivel executar o comando: \n" + sqlex + "\n o sql passado foi: \n" + sql);     } } ``

minha class onde se encontra o metodo EXECUTESQL: p

``ublic class ConnectionFactory {      private static final String DRIVER = "com.mysql.jdbc.Driver";     private static final String URL = "jdbc:mysql://localhost:3306/helpsemeq"+"?verifyServerCertificate=false&useSSL=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=America/Sao_Paulo";     private static final String USER = "root";     private static final String PASS = "";     private static Connection conexao;     public Statement statement;     public ResultSet resultset;      public boolean getConnection() {         boolean result = true;         try {             Class.forName(DRIVER);             conexao = DriverManager.getConnection(URL, USER, PASS);             result = true;         } catch (ClassNotFoundException | SQLException ex) {             result = false;             throw new RuntimeException("Erro na conexão: ", ex);         }         return result;     }      public static void closeConnection(Connection con) {         try {             if (con != null) {                 con.close();             }         } catch (SQLException ex) {             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);         }     }      public static void closeConnection(Connection con, PreparedStatement stmt) {         closeConnection(con);         try {             if (stmt != null) {                 stmt.close();             }         } catch (SQLException ex) {             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);         }     }      public static void closeConnection(Connection con, PreparedStatement stmt, ResultSet rs) {         closeConnection(con, stmt);         try {             if (rs != null) {                 rs.close();             }         } catch (SQLException ex) {             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);         }     }      public void executeSQL(String sql) {         try {             statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);             resultset = statement.executeQuery(sql);         } catch (SQLException sqlex) {             System.out.println("Não foi possivel executar o comando: \n" + sqlex + "\n o sql passado foi: \n" + sql);         }     } } ``

não sei se isso está relacionado a threads ou é algum problema no codigo

os erros ao compilar:

``Caused by: java.lang.reflect.InvocationTargetException Caused by: java.lang.NullPointerException ``

se tiver como alguém me dar uma luz pff.

I’ve just discovered Threads on Twitter and found that they could be a great way of keeping a daily feed of events related to one thing, but there are a problems, and I was wondering if there was a practical solution to them.

So lets say you’re doing a daily `24 Hours In The Life of Garden Birds` for a month. Ideally your first tweet would be an intorduction, and then the rest would be a summary of each hour. Followers would get an easy to read, hour by hour summary posted in time order.

The problem is, non followers who visit your profile see a long list of 25 individual tweets, posted in reverse order with the introduction last – Making your timeline look a bit crap to outsiders.

I figured a practical solution may be to have 2 accounts:

`@24HoursOfBirds` – A secondary account for posting the threads.

`@Birds` – The main account for retweeting the first tweet of each thread + important tweets that are not seen in thread format.

The problem of course is that all of your engagements are going to be made on the Secondary (`@24HoursOfBirds`) account, and you’re likely to make all of your followers in this account too.

Is there a way to make threads appear a little bit more asthetically pleasing to visitors to your profile?