1.多线程基础

2017-09-08  本文已影响6人  765197250c12

多线程概念

QQ就是一个进程,可以同时和好友聊天,同时下载文件或者发送表情。不同的操作可以同时进行。这些一个个的操作可以理解成为线程。

优点 ‘同一时间’进行多个任务,提高CPU利用效率。

图1-1 单任务 图1-2 多任务

多线程使用

在java中实现多线程的方式有两种,一种继承Thread类,另一种实现Runnable接口。

方式1

com.gu包下文件MyThread.java
package com.gu;

/**
 * Created by gurongkang on 2017/9/7.
 */
public class MyThread extends Thread {

  @Override
  public void run() {
    super.run();
    System.out.println("MyThread");
  }
}

com.gu包下文件Main.java
package com.gu;

public class Main {

  public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.start();
    System.out.println("main over");
  }
}

方式2
实现Runnable接口。

com.gu包下文件MyRunnable.java
package com.gu;

/**
 * Created by gurongkang on 2017/9/7.
 */
public class MyRunnable implements Runnable {

  @Override
  public void run() {
    System.out.println("running");
  }
}

如何使用,查看JDK文档如图1-3

图1-3 Thread构造函数

8个构造函数中,其中两个构造函数 Thread(Runnable target)Thread(Runnable target, String name),可以传递Runnable接口。

测试代码

com.gu包下文件main.java
package com.gu;

public class Main {

  public static void main(String[] args) {
//    MyThread myThread = new MyThread();
//    myThread.start();
//    System.out.println("main over");
    testRunnable();
  }


  static void testRunnable() {
    Runnable runnable = new MyRunnable();
    Thread thread = new Thread(runnable);
    thread.start();
    System.out.println("main over");
  }
}

实例变量线程安全

自定义线程类中的实例变量针对其他线程可以有共享和不共享之分,多个线程之间交互需要注意。
测试代码

package com.gu;

/**
* Created by gurongkang on 2017/9/10.
*/
public class LocalThread extends Thread {

 private int count = 5;

 public LocalThread() {
   super();
 }

 public LocalThread(String name) {
   super();
   this.setName(name);
 }

 @Override
 public void run() {
   super.run();
   while (count > 0) {
     count--;
     System.out.println(this.currentThread().getName() + " count = " + count);
   }
 }
}

(1)不共享数据

  static void testNotShareLocal() {
    Thread thread = new LocalThread("A");
    Thread thread1 = new LocalThread("B");
    Thread thread2 = new LocalThread("C");
    thread.start();
    thread1.start();
    thread2.start();
  }
不共享数据

(2)共享数据

  static void testShareLocal() {
    LocalThread localThread = new LocalThread();
    Thread thread = new Thread(localThread, "A");
    Thread thread1 = new Thread(localThread, "B");
    Thread thread2 = new Thread(localThread, "C");
    thread.start();
    thread1.start();
    thread2.start();
  }
上一篇下一篇

猜你喜欢

热点阅读