多线程执行多任务

多线程执行多任务

如何通过多线程执行单个任务?

如果必须由多个线程执行单个任务,则只有通过run()方法。例如:
由多个线程执行单个任务的程序。

package com.zyiz;

class TestMultitasking1 extends Thread {
    public void run() {
        System.out.println("task one");
    }

    public static void main(String args[]) {
        TestMultitasking1 t1 = new TestMultitasking1();
        TestMultitasking1 t2 = new TestMultitasking1();
        TestMultitasking1 t3 = new TestMultitasking1();

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

执行上面示例代码,得到以下结果:

task one
task one
task one

多个线程执行单个任务的程序 -

package com.zyiz;

class TestMultitasking2 implements Runnable {
    public void run() {
        System.out.println("task one");
    }

    public static void main(String args[]) {
        Thread t1 = new Thread(new TestMultitasking2());// passing annonymous object of TestMultitasking2 class
        Thread t2 = new Thread(new TestMultitasking2());

        t1.start();
        t2.start();

    }
}

执行上面示例代码,得到以下结果:

task one
task one

注意: 每个线程都在一个单独的调用堆栈中运行。

如何通过多线程执行多个任务(多线程中的多任务处理)?

如果想要通过多个线程执行多个任务,请使用多个run()方法。例如:
通过两个线程执行两个任务的程序 -

package com.zyiz;

class Simple1 extends Thread {
    public void run() {
        System.out.println("task one");
    }
}

class Simple2 extends Thread {
    public void run() {
        System.out.println("task two");
    }
}

class TestMultitasking3 {
    public static void main(String args[]) {
        Simple1 t1 = new Simple1();
        Simple2 t2 = new Simple2();

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

执行上面示例代码,得到以下结果:

task two
task one

使用扩展Thread类的匿名类相同的例子:

通过两个线程执行两个任务的程序 -

class TestMultitasking4 {
    public static void main(String args[]) {
        Thread t1 = new Thread() {
            public void run() {
                System.out.println("task one");
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                System.out.println("task two");
            }
        };

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

执行上面示例代码,得到以下结果:

task two
task one

使用实现Runnable接口的相同例子:

通过两个线程执行两个任务的程序 -

class TestMultitasking5{  
 public static void main(String args[]){  
  Runnable r1=new Runnable(){  
    public void run(){  
      System.out.println("task one");  
    }  
  };  

  Runnable r2=new Runnable(){  
    public void run(){  
      System.out.println("task two");  
    }  
  };  

  Thread t1=new Thread(r1);  
  Thread t2=new Thread(r2);  

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

执行上面示例代码,得到以下结果:

task two
task one