java 通过Thread实现多线程

来源:互联网 发布:企业积分制管理 知乎 编辑:程序博客网 时间:2024/04/30 00:35

1. Thread

 

getID()

获取线程ID

getName(), setName()

获取和设置线程名。

getPriority(),  setPriority()

获取和设置线程优先级。

getState()

获取线程状态。

getThreadGroup()

获取线程所在的线程组。

isAlive()

获取线程是否已经启动并且没有终止。

isDaemon(), setDaemon()

获取和设置线程是否为守护线程。

isInterrupted()

获取线程是否被中断。

 

start()

开始线程。

join()

等待指定线程中终止。

interrupt()

中断线程

 

静态方法

currentThread()

获取当前线程。

sleep()

使当前线程休眠指定的时间。

yield()

使当前线程暂停执行,让其它等待的线程执行。

interrupted()

获取当前线程是否被中断。

 

 

 

2. 通过Thread实现多线程

1. 通过继承Thread类并覆盖Threadrun()方法创建一个新的线程类。

2. 使用该线程类创建线程对象。

  1. public class ThreadTest
  2. {
  3.     public static void main(String[] args) throws Exception
  4.     {
  5.         TestThread th = new TestThread("thread 1");
  6.         th.start();
  7.         th.join();
  8.         System.out.println("'main' ended.");
  9.     }
  10.     
  11.     private static class TestThread extends Thread
  12.     {
  13.         public TestThread(String threadName)
  14.         {
  15.             super(threadName);
  16.         }
  17.         
  18.         @Override
  19.         public void run()
  20.         {
  21.             String thName = Thread.currentThread().getName();
  22.             System.out.printf("'%s' started. /n", thName);
  23.             for (int i = 0; i < 10; i++)
  24.             {
  25.                 System.out.println(i);
  26.             }
  27.             System.out.printf("'%s' ended. /n", thName);
  28.         }
  29.     }
  30. }

 

3. 通过Runnable实现多线程

1. 创建一个Runnable接口的实现类(实现run()方法)。

2. 通过Thread类包含Runnable的构造方法创建线程对象。

  Thread(Runnable target)

  Thread(ThreadGroup group, Runnable target)

  ThreadGroup group, Runnable target, String name)

  1. public class RunnableTest
  2. {
  3.     public static void main(String[] args) throws Exception
  4.     {
  5.         Thread th = new Thread(new TestRunnable(), "thread 1");
  6.         th.start();
  7.         th.join();
  8.         System.out.println("'main' ended.");
  9.     }
  10.     
  11.     private static class TestRunnable implements Runnable
  12.     {
  13.         @Override
  14.         public void run()
  15.         {
  16.             String thName = Thread.currentThread().getName();
  17.             System.out.printf("'%s' started. /n", thName);
  18.             for (int i = 0; i < 10; i++)
  19.             {
  20.                 System.out.println(i);
  21.             }
  22.             System.out.printf("'%s' ended. /n", thName);
  23.         }
  24.     }
  25. }

 

4. ThreadGroup

activeCount()

获取线程组中正在执行的线程数量。

activeGroupCount()

获取线程组中正在执行的线程组数量。

getMaxPriority(), setMaxPriority()

获取和设置最大优先级

getName()

获取线程组的名称。

getParent()

获取父线程组

interrupt()

中断线程组中的所有线程。

isDaemon(), setDaemon()

获取和设置线程组是否为守护线程。

parentOf(ThreadGroup)

判断线程组是否包含于指定线程组中。

 

 

5. 通过ThreadGroup管理线程

在创建线程对象时,通过包含ThreadGroup的构造方法创建,将线程加入指定线程组

  Thread(ThreadGroup group, Runnable target)

  Thread(ThreadGroup group, Runnable target, String name)

  Thread(ThreadGroup group, String name)

  1. public class ThreadGroupTest
  2. {
  3.     
  4.     public static void main(String[] args) throws Exception
  5.     {
  6.         // 创建线程组对象。
  7.         ThreadGroup tg = new ThreadGroup("group 1");
  8.         
  9.         // 向线程组中加入10个线程。
  10.         for (int i = 0; i < 10; i++)
  11.         {
  12.             Thread th = new Thread(tg, new TestRunnable(), "thread " + i);
  13.             th.start();
  14.         }
  15.         
  16.         // 等待2秒。
  17.         Thread.sleep(2000);
  18.         
  19.         // 中断所有线程。
  20.         tg.interrupt();
  21.         
  22.         // 输出
  23.         System.out.println(tg.activeCount());
  24.     }
  25.     
  26.     private static class TestRunnable implements Runnable
  27.     {
  28.         @Override
  29.         public void run()
  30.         {
  31.             String thName = Thread.currentThread().getName();
  32.             System.out.printf("'%s' started. /n", thName);
  33.             while (!Thread.currentThread().isInterrupted())
  34.             {
  35.             }
  36.             System.out.printf("'%s' ended. /n", thName);
  37.         }
  38.     }
  39. }

PART.2  通过Callable和FutureTask实现异步调用

 

1. Callable<V>

Ø  V为返回值的类型。

Ø  实现Callable接口需实现call方法。

Ø  Runnablerun方法相比,call方法具有返回值V和异常声明。

 

 

2. FutureTask<V>

V为返回值得类型。

cancel()

取消执行。

get()

阻塞获取执行结果。

get(long, TimeUnit)

指定阻塞的最长时间,获取执行结果。

isCancelled()

获取是否被取消。

isDone()

获取是否完成。

run()

开始执行。

 

 

3. 通过Callable和FutureTask异步执行

1. 创建一个Callable<V>的实现类。

2. 创建FutureTask<V>对象。

3. 执行创建的FutureTask对象。(run方法)

4. 通过FutureTask对象获取结果。(get方法)

  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.FutureTask;
  4. public class FutureTaskTest
  5. {
  6.     public static void main(String[] args)
  7.     {
  8.         FutureTask<Integer> ct = null;
  9.         
  10.         ct = new FutureTask<Integer>(new TestCallable());
  11.         ct.run();
  12.         
  13.         try
  14.         {
  15.             int ret = ct.get();
  16.             System.out.println(ret);
  17.         }
  18.         catch (InterruptedException e)
  19.         {
  20.             // ct.get() 时线程被中断。 
  21.             e.printStackTrace();
  22.         }
  23.         catch (ExecutionException e)
  24.         {
  25.             // Callable在执行时出现异常。
  26.             e.printStackTrace();
  27.         }
  28.     }
  29.     private static class TestCallable implements Callable<Integer>
  30.     {
  31.         @Override
  32.         public Integer call() throws Exception
  33.         {
  34.             double i = Math.random() * 100;
  35.             return (int)i;
  36.         }
  37.     }
  38. }

4.处理FutureTask执行时发生的异常

  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.FutureTask;
  4. public class FutureTaskExceptionTest
  5. {
  6.     public static void main(String[] args)
  7.     {
  8.         FutureTask<Integer> ct = null;
  9.         
  10.         ct = new FutureTask<Integer>(new TestCallable());
  11.         ct.run();
  12.         
  13.         try
  14.         {
  15.             int ret = ct.get();
  16.             System.out.println(ret);
  17.         }
  18.         catch (InterruptedException e)
  19.         {
  20.             // ct.get() 时线程被中断。 
  21.             e.printStackTrace();
  22.         }
  23.         catch (ExecutionException e)
  24.         {
  25.             // Callable在执行时出现异常。
  26.             System.out.println(e.getCause().getMessage());
  27.             System.out.println(e.getMessage());
  28.         }
  29.     }
  30.     private static class TestCallable implements Callable<Integer>
  31.     {
  32.         @Override
  33.         public Integer call() throws Exception
  34.         {
  35.             throw new Exception("An test exception.");
  36.         }
  37.     }
  38. }

PART.3  通过ExecutorService实现多线程

 

1. ExecutorService

awaitTermination

等待所有任务结束。

invokeAll

执行集合中的所有任务,返回所有Future。该方法将等待所有任务结束或指定的时间。

invokeAny

执行集合中的一个任务,返回该任务得返回值。

isShutdown

获取ExecutorService是否被shutdown

isTerminated

获取是否所有任务已经结束。

Shutdown

等待所有正在执行的任务结束。将没有执行的任务返回。不执行后新的任务。

shutdownNow

中断正在执行的任务。返回没有执行的任务。

submit

提交一个任务并开始执行。

 

2. 创建ExecutorService

Executors.newCachedThreadPool

Executors.newFixedThreadPool

Executors.newScheduledThreadPool

Executors.newSingleThreadExecutor

Executors.newSingleThreadScheduledExecutor

 

 

3. 通过ExecutorService实现多线程

1. 创建ExecutorService对象。

2. ExecutorServices对象提交任务。

3. 获得结果。

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.Future;
  7. public class ExecutorServiceTest
  8. {
  9.     public static void main(String[] args) throws Exception
  10.     {
  11.         ExecutorService es = Executors.newCachedThreadPool();
  12.         
  13.         // 创建10个任务,将这些任务交由ExecutorService执行,保存这些任务的Future到List。
  14.         List<Future<Integer>> fs = new ArrayList<Future<Integer>>(10); 
  15.         for (int i = 0; i < 10; i++)
  16.         {
  17.             TestCallable t = new TestCallable();
  18.             Future<Integer> f = es.submit(t);
  19.             fs.add(f);
  20.         }
  21.         
  22.         // 等待执行结束。
  23.         Thread.sleep(1000);
  24.         
  25.         // 输出执行结果。
  26.         for (Future<Integer> f : fs)
  27.         {
  28.             System.out.println(f.get());
  29.         }
  30.         
  31.         // 关闭ExecutorService。
  32.         es.shutdown();
  33.     }
  34.     
  35.     private static class TestCallable implements Callable<Integer>
  36.     {
  37.         @Override
  38.         public Integer call() throws Exception
  39.         {
  40.             double ret = Math.random() * 100;
  41.             return (int)ret;
  42.         }
  43.     }
  44. }

4. 关闭ExecutorService

shutdown()                等待任务结束

shutdownNow()       中断任务

 

  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. public class ExecutorServiceShutdownTest
  5. {
  6.     public static void main(String[] args) throws Exception
  7.     {
  8.         // PART 1  测试shutdownNow()。
  9.         System.out.println("----- PART 1");
  10.         
  11.         // 创建ExecutorService。
  12.         ExecutorService es = Executors.newCachedThreadPool();
  13.         
  14.         // 开始10个任务。
  15.         System.out.println("----- Start all tasks...");
  16.         for (int i = 0; i < 10; i++)
  17.         {
  18.             TestCallable task = new TestCallable("task " + i);
  19.             es.submit(task);
  20.         }
  21.         
  22.         // 等待5秒。在此期间可能有任务结束。
  23.         System.out.println("----- Wait for 5 seconds.");
  24.         Thread.sleep(5000);
  25.         
  26.         // 结束所有任务。
  27.         System.out.println("----- Shutdown all tasks now.");
  28.         es.shutdownNow();
  29.         
  30.         System.out.println("----- End of PART 1");
  31.         Thread.sleep(1000);
  32.         
  33.         // 测试shutdown()。 
  34.         System.out.println("----- PART 2");
  35.         Thread.sleep(1000);
  36.         // 创建ExecutorService。
  37.         es = Executors.newCachedThreadPool();
  38.         
  39.         // 开始10个任务。
  40.         System.out.println("----- Start all tasks...");
  41.         for (int i = 0; i < 10; i++)
  42.         {
  43.             TestCallable task = new TestCallable("task " + i);
  44.             es.submit(task);
  45.         }
  46.         // 等待5秒。在此期间可能有任务结束。
  47.         System.out.println("----- Wait for 5 seconds.");
  48.         Thread.sleep(5000);
  49.         
  50.         // 结束所有任务。
  51.         System.out.println("----- Shutdown all tasks.");
  52.         es.shutdown();
  53.     
  54.         System.out.println("----- End of main.");
  55.     }
  56.     private static class TestCallable implements Callable<Void>
  57.     {
  58.         private String name;
  59.         
  60.         public TestCallable(String name)
  61.         {
  62.             this.name = name;
  63.         }
  64.         
  65.         @Override
  66.         public Void call() throws Exception
  67.         {
  68.             System.out.printf("'%s' started. /n", name);
  69.             
  70.             // 等待3 - 12秒。
  71.             try
  72.             {
  73.                 
  74.                 int w = (int)(Math.random() * 10 + 3);
  75.                 Thread.sleep(w*1000);
  76.             }
  77.             catch (InterruptedException e)
  78.             {
  79.                 System.out.printf("'%s' interrupted. /n", name);
  80.             }
  81.             
  82.             System.out.printf("'%s' ended. /n", name);
  83.             return null;
  84.         }
  85.     }
  86. }
0 0
原创粉丝点击