如何正确使用java多线程?

时间:2017-08-18 00:36:35

标签: java multithreading

我在互联网上的很多例子几乎都是一样的:

public class Test extends Thread {
    public synchronized void run() {
        for (int i = 0; i <= 10; i++) {
            System.out.println("i::"+i);
        }
    }

    public static void main(String[] args) {
        Test obj = new Test();

        Thread t1 = new Thread(obj);
        Thread t2 = new Thread(obj);
        Thread t3 = new Thread(obj);

        t1.start();
        t2.start();
        t3.start();
    }
}

那么为什么我会用不同的线程调用相同的任务(在run()方法中)三次?例如。如果我想上传文件,为什么我会打三次? 我假设我需要多线程:

thread t1 would do task1, e.g.:
   - update database info
thread t2 would do task2, e.g.:
   - upload file to server
thread t3 would do task3, e.g.:
   - bring a message to an user

是否有一个可以像上面描述的那样工作的例子。

1 个答案:

答案 0 :(得分:0)

您可以创建下面给出的代码的多个线程,您只需启动线程,而不需要多次使用相同的方法调用。如您所见,一旦启动,所有三个子线程共享CPU。注意main()中的sleep(10000)调用。这会导致主线程休眠十秒钟并确保它最后完成。

     // Create multiple threads.
         class NewThread implements Runnable
            { 
                String name;
            } // name of thread Thread t;
              NewThread(String threadname) 
              { 
                  name = threadname;
              } 
              t = new Thread(this, name); 
              System.out.println("New thread: " + t); 
              t.start(); // Start the thread 
        }
    // This is the entry point for thread.
        public void run() 
        {
            try 
            { 
                for(int i = 5; i > 0; i--)
                {
                    System.out.println(name + ": " + i); 
                    Thread.sleep(1000);
                } 
            } catch (InterruptedException e) 
            {
                System.out.println(name + "Interrupted");
            } 
            System.out.println(name + " exiting."); 
        }
    }
    class MultiThreadDemo 
    { 
        public static void main(String args[]) 
        { 
            new NewThread("One"); // start threads
            new NewThread("Two"); 
            new NewThread("Three");
        try 
        { 
            // wait for other threads to end
            Thread.sleep(10000); 
        }
        catch (InterruptedException e) 
        { 
            System.out.println("Main thread Interrupted"); 
        }
        System.out.println("Main thread exiting.");
        }
        }

完整参考文献Herbert Schildt的参考资料