java多线程简单Demo

港控/mmm° 2022-11-14 10:28 305阅读 0赞

TestThr.java;

  1. class Mythread implements Runnable {
  2. private Thread t;
  3. private String threadName;
  4. Mythread( String name) {
  5. threadName = name;
  6. System.out.println("Creating " + threadName );
  7. }
  8. public void run() {
  9. System.out.println("Running " + threadName );
  10. try {
  11. for(int i = 5; i > 0; i--) {
  12. System.out.println("Thread: " + threadName + ", " + i);
  13. // 让线程睡眠一会
  14. Thread.sleep(50);
  15. }
  16. }catch (InterruptedException e) {
  17. System.out.println("Thread " + threadName + " interrupted.");
  18. }
  19. System.out.println("Thread " + threadName + " exiting.");
  20. }
  21. public void start () {
  22. System.out.println("Starting " + threadName );
  23. if (t == null) {
  24. t = new Thread (this, threadName);
  25. t.start ();
  26. }
  27. }
  28. }
  29. public class TestThr{
  30. public static void main(String args[]) {
  31. Mythread t1 = new Mythread( "Thread-1");
  32. t1.start();
  33. Mythread t2 = new Mythread( "Thread-2");
  34. t2.start();
  35. }
  36. }

构建和运行情况如下;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JjYm9ibzIxY24_size_16_color_FFFFFF_t_70

在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java线简单实例

    最近为了提高批处理程序的统计效率,将程序改为多线程执行,由原来的单一线程计算改为五个线程同时计算,大大缩短了统计时间。实现原理很简单,就是将需要计算的内容分成五份交给五个线程进