简体   繁体   English

同时运行线程

[英]run threads simultaneously

I have the next code: 我有下一个代码:

    public class App 
{
    public static void main( String[] args )
    {
        NewSmartThread n = new NewSmartThread("ST");
        try{
            n.join();
        }catch(InterruptedException e){
            System.out.println( "Умный поток был прерван" );
        }
        System.out.println( "Hello World!" );
    }
}

class NewSimpleThread extends Thread {

    public NewSimpleThread(String name){
        super(name);
    }

    public void run(){
            try {
                for(int i =1; i<6; i++)
                {
                    System.out.println("Thread " + this.getName() + " : " + i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                System.out.println("Thread " + this.getName() + "был прерван.");
            }
        System.out.println("Thread " + this.getName() + " closed.");
}
}

class NewSmartThread extends Thread {
    //final CountDownLatch start = new CountDownLatch(1);
    //final CountDownLatch finish = new CountDownLatch(2);

    public NewSmartThread(String name) {
        super(name);
        start();
    }

    public void run(){
        //s1.split("(?<=\\G..)")

        NewSimpleThread n1 = new NewSimpleThread("1");
        NewSimpleThread n2 = new NewSimpleThread("2");
        NewSimpleThread n3 = new NewSimpleThread("3");

        n1.start();
        n2.start();
        n3.start();
        try{

            Thread.sleep(3000);


            n1.join();
            n2.join();
            n3.join();
        }catch(InterruptedException e){
            System.out.println("Thread " + "broke.");
        }
        System.out.println("Smart thread " + this.getName() + " closed.");
    }
}

And I have the next result: 我得到下一个结果:

>     Thread 2 : 1
>     Thread 3 : 1
>     Thread 1 : 1
>     Thread 3 : 2
>     Thread 1 : 2
>     Thread 2 : 2
>     Thread 2 : 3
>     Thread 1 : 3
>     Thread 3 : 3
>     Thread 2 : 4
>     Thread 1 : 4
>     Thread 3 : 4
>     Thread 1 : 5
>     Thread 2 : 5
>     Thread 3 : 5
>     Thread 1 closed.
>     Thread 2 closed.
>     Thread 3 closed.
>     Smart thread ST closed.
>     Hello World!

But if I use block synchronized in the next code: 但是,如果我在下一个代码中使用块同步:

public class App 
{
    public static void main( String[] args )
    {
        NewSmartThread n = new NewSmartThread("ST");
        try{
            n.join();
        }catch(InterruptedException e){
            System.out.println( "Умный поток был прерван" );
        }
        System.out.println( "Hello World!" );
    }
}

class NewSimpleThread extends Thread {
    private static final Object monitor = new Object();
    public NewSimpleThread(String name){
        super(name);
    }

    public void run(){
        synchronized (monitor) {
            try {
                monitor.wait();
                for(int i =1; i<6; i++)
                {
                    System.out.println("Thread " + this.getName() + " : " + i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println("Thread " + this.getName() + " closed.");
        }
    }

    public static void doNotifyAll(){
        synchronized (monitor) {
            monitor.notifyAll();
        }
    }
}
class NewSmartThread extends Thread {

    public NewSmartThread(String name) {
        super(name);
        start();
    }

    public void run(){
        NewSimpleThread n1 = new NewSimpleThread("1");
        NewSimpleThread n2 = new NewSimpleThread("2");
        NewSimpleThread n3 = new NewSimpleThread("3");

        n1.start();
        n2.start();
        n3.start();
        try{

            Thread.sleep(3000);
            NewSimpleThread.doNotifyAll();

            n1.join();
            n2.join();
            n3.join();
        }catch(InterruptedException e){
            System.out.println("Thread " + "broke.");
        }
        System.out.println("Smart thread " + this.getName() + " closed.");
    }
}

And have the next result: 并得到下一个结果:

 Thread 3 : 1 Thread 3 : 2 Thread 3 : 3 Thread 3 : 4 Thread 3 : 5 Thread 3 closed. Thread 2 : 1 Thread 2 : 2 Thread 2 : 3 Thread 2 : 4 Thread 2 : 5 Thread 2 closed. Thread 1 : 1 Thread 1 : 2 Thread 1 : 3 Thread 1 : 4 Thread 1 : 5 Thread 1 closed. Smart thread ST closed. Hello World! 

But I need the result like in the first example. 但是我需要像第一个示例中那样的结果。 And can't use some features like CountDownLatch - only synchronized block(It is lab experiment and it is a requirenment) 并且不能使用CountDownLatch之类的某些功能-仅同步块(这是实验室实验,这是必需项)

Does anyone know how to do this? 有谁知道如何做到这一点?

If I understand the question correctly then the issue lies in how you have used the synchronized block in the second example. 如果我正确理解了问题,那么问题就出在第二个示例中,您如何使用同步块。

You have synchronized the whole logic including the for loop inside synchronized block. 您已synchronized了整个逻辑,包括同步块内的for循环。 While the correct way would be to just keep 正确的方法是保持

synchronized(monitor){
    monitor.wait(); //excluding exception handling
}

//for loop logic

Why? 为什么?

Because you just want the threads to wait for the nod of the main thread to start working and once they get the notification you dont want the logic to be executed in synchronized manner and so release the monitor . 因为您只希望线程等待主线程开始工作,并且一旦它们收到通知,您就不希望逻辑以synchronized方式执行,因此释放监视器 Because you hold the monitor while for loop, no other thread is able to proceed until the one holding it completes. 因为您在for循环时按住监视器,所以其他线程无法继续进行直到持有该监视器的线程完成。

Thanks for Narendra Pathai. 感谢Narendra Pathai。

The ended variant of my code the next: 我的代码的结束变种如下:

public class App 
{
    public static void main( String[] args )
    {
        NewSmartThread n = new NewSmartThread("ST");
        try{
            n.join();
        }catch(InterruptedException e){
            System.out.println( "Умный поток был прерван" );
        }
        System.out.println( "Hello World!" );
    }
}

class NewSimpleThread extends Thread {
    private static final Object monitor = new Object();
    public NewSimpleThread(String name){
        super(name);
    }

    public void run(){
        try {
            Latch.awaitZero();
            for(int i =1; i<6; i++)
            {
                System.out.println("Thread " + this.getName() + " : " + i);
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread " + this.getName() + " closed.");
    }

    public static void doNotifyAll(){
        synchronized (monitor) {
            monitor.notifyAll();
        }
    }
}
class NewSmartThread extends Thread {

    public NewSmartThread(String name) {
        super(name);
        start();
    }

    public void run(){
        NewSimpleThread n1 = new NewSimpleThread("1");
        NewSimpleThread n2 = new NewSimpleThread("2");
        NewSimpleThread n3 = new NewSimpleThread("3");

        n1.start();
        n2.start();
        n3.start();
        try{

            Thread.sleep(3000);
            Latch.doNotifyAll();

            n1.join();
            n2.join();
            n3.join();
        }catch(InterruptedException e){
            System.out.println("Thread " + "broke.");
        }
        System.out.println("Smart thread " + this.getName() + " closed.");
    }
}

class Latch {
    private static final Object synchObj = new Object();

    public static void awaitZero() throws InterruptedException {
        synchronized (synchObj) {
                synchObj.wait();
        }
    }
    public static void doNotifyAll() {
        synchronized (synchObj) {
                synchObj.notifyAll();
        }
    }
}

I added class: 我添加了课程:

class Latch {
    private static final Object synchObj = new Object();

    public static void awaitZero() throws InterruptedException {
        synchronized (synchObj) {
                synchObj.wait();
        }
    }
    public static void doNotifyAll() {
        synchronized (synchObj) {
                synchObj.notifyAll();
        }
    }
}

instead 代替

class NewSimpleThread extends Thread {
    private static final Object monitor = new Object();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM