JAVA多线程

一个程序就是一个进程,而一个程序中的多个任务则被称为线程。

JAVA使用多线程

1.继承Thread类

2.实现Runnable接口

线程安全

synchronized关键字

实例变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ThreadTest implements Runnable{
private int count = 100;

@Override
public void run() {
count --;
System.out.println(Thread.currentThread().getName() + "---:" + count);
}

public static void main(String args[]) {
ThreadTest myThread = new ThreadTest();
Thread a = new Thread(myThread,"A");
Thread b = new Thread(myThread,"B");
Thread c = new Thread(myThread,"C");
Thread d = new Thread(myThread,"D");

a.start();
b.start();
c.start();
d.start();

System.out.println("--------------");

ThreadTest myThread2 = new ThreadTest();
Thread a2 = new Thread(myThread2,"A2");

a2.start();
}
}

运行结果:

1
2
3
4
5
6
7
--------------
C---:98
A---:98
B---:97
B1---:98
A1---:99
D---:96

a,b,c,d线程使用共享变量count。线程a1,b1与线程a,b,c,d不使用共享变量。可以使用synchronized关键字使各个线程排队执行run()方法synchronized public void run() {

结束线程的方法

  1. 使用标志位终止线程还可以线程中去数据库读取本任务的状态信息判断是否退出

    1
    2
    3
    4
    public volatile boolean exit = false;
    public void setExit(boolean exit) {
    this.exit = exit;
    }
  2. interrupt()中断线程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public class InterruptThreadTest extends Thread {
    public static void main(String[] args) {
    try {
    InterruptThreadTest t = new InterruptThreadTest();
    t.start();
    Thread.sleep(200);
    t.interrupt();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    @Override
    public void run() {
    for (int i = 0; i <= 100000; i++) {
    if (Thread.currentThread().isInterrupted()) {
    break;
    }
    System.out.println("i=" + i);
    }
    }
    }