Java thread request

Im working on a Java application that includes threads. So I just wrote a code snippet to just get familiar with running multiple simultaneous threads

public class thready implements Runnable{
private int num;

public thready(int a) {
    this.num=a;
}
public void run() {
  System.out.println("This is thread num"+num);
  for (int i=num;i<100;i++)
  {
      System.out.println(i);
  }
}
public static void main(String [] args)
{
    Runnable runnable =new thready(1);
    Runnable run= new thready(2);
    Thread t1=new Thread(runnable);
    Thread t2=new Thread(run);
    t1.start();
    t2.start();
}}

Now, from the output of this code, I think that only one thread is executed at any given time, and the execution seems to alternate between threads. Now I would like to know if I understand the situation correctly. And if so, I would like to know if there is any way that I could start both threads at the same time, since I want to enable this scenario in a situation where I want to write a tcp / ip socket listener that simultaneously listens on 2 ports , in the same time. And such a scenario has no downtime. Any suggestions / recommendations would be very helpful.

Greetings

+2
10

? , . - , , , .

- . , . ( "" , ), - .

, . , . , , - , .

EDIT: ( ), , , . , , .

+5

, . , -, CPU. , JVM . ( CPU), ( : , ).

, TCP/IP-.

+1

println. , , .

0

- , /. , /.

( ), , , . , .

0

, . 100 , , , , , , .

, , , , , , . , , .

, , , . , , System.out.println, , . , .

0

, .

run :

public void run() {
   for (int i=num;i<100;i++) {
      try {
         Thread.sleep(100);
         System.out.println("Thread " + num + ": " + i);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }  
   }
}
0

, , . , , . - .

Java 5 ​​ , ( Runnable). . , . , .

http://dudefrommangalore.blogspot.com/2010/01/concurrency-in-java.html

Cheers, - baliga

0

2 . JVM, JVM 2 , .

, , , . , , , .

- . , .

0

:

  • System.out.println() , flush(), .
  • - System.out , , , . System.out , Sytem.err - .
0

Source: https://habr.com/ru/post/1729535/


All Articles