1、特点
不用继承Thread类、能实现资源共享
2、基本例子
public class Run implements Runnable {
private int count = 1;
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + " 运行 " + count++);//获取当前执行这段代码的线程的名字,且变量自增
}
}
public static void start() {
Run r = new Run();
new Thread(r, "线程A").start();
new Thread(r, "线程B").start();
new Thread(r, "线程C").start();
}
}
3、多线程中使用synchronized(锁)
上面例子中的代码,如果不使用synchronized线程是不安全,因为多个线程有可能在同一时间操作变量,就会导致执行两次结果只自增1。所以可以用synchronized来实现线程安全,让变量在同一时间只让一个线程操作。
public class Run implements Runnable {
public static void start() {
Run aa = new Run();
new Thread(aa, "线程A").start();
new Thread(aa, "线程B").start();
new Thread(aa, "线程C").start();
}
private int count = 1;
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 100000; i++) {
System.out.println(Thread.currentThread().getName() + " 运行 " + count++);//获取当前执行这段代码的线程的名字,变量自增
}
}
}
}
4、多线程中使用原子类型AtomicInteger
另一种保证线程安全的方法,JDK1.5之后引入一批原子处理类:AtomicBoolean、AtomicInteger、AtomicLong、AtomicReference。主要用于在高并发环境下的高效程序处理,来帮助我们简化同步处理.
public class Run implements Runnable {
public static void start() {
Run aa = new Run();
new Thread(aa, "线程A").start();
new Thread(aa, "线程B").start();
new Thread(aa, "线程C").start();
}
private AtomicInteger count = new AtomicInteger(1);
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + " 运行 " + count.getAndIncrement());
}
}
}
5、用匿名内部类的方式实现Runnble接口
public class Run {
public static void test() {
Run r = new Run();
new Thread(r.runnable, "线程A").start();
new Thread(r.runnable, "线程B").start();
}
private int count = 1;
public Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " 运行 " + count++);//获取当前执行这段代码的线程的名字,变量自增
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
6、用 匿名内部类+lambda表达式 的方式实现Runnble接口
public class Run {
public static void test() {
Run r = new Run();
new Thread(r.runnable, "线程A").start();
new Thread(r.runnable, "线程B").start();
}
private int count = 1;
public Runnable runnable = () -> {
for (int i = 0; i < 10; i++) {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " 运行 " + count++);//获取当前执行这段代码的线程的名字,变量自增
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}