线程的创建方式
继承Thread类
public class ThreadCreateDemo1 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); //该方法调用多次,出现IllegalThreadStateException
}
}
class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("hellow_world!");
}
}
继承Runnable接口
public class ThreadCreateDemo2 {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
new Thread(runnable).start();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("通过Runnable创建的线程!");
}
}
上述两种创建方式,工作时性质一样。但是建议使用实现Runable接口方式。解决单继承的局限性
线程运行结果与执行顺序无关
线程的调度是由CPU决定,CPU执行子任务时间具有不确定性。
public class ThreadRandomDemo1 {
public static void main(String[] args) {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new RandomThread("RandomThread:" + i);
}
for(Thread thread : threads) {
thread.start();
}
}
}
class RandomThread extends Thread {
public RandomThread(String name) {
super(name);
}
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
以上10个线程,代码按照顺序执行,但是结果可以看出没有按照顺序执行,而且多次执行结果基本不同。
线程实例变量与安全问题
线程之间变量有共享与不共享之分,共享理解为大家都使用同一份,不共享理解为每个单独持有一份。
共享数据的情况
public class ThreadShareVariableDemo {
public static void main(String[] args) {
Runnable runnable = new ShareVariableRunnable();
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new Thread(runnable, "thread:" + (i+1));
}
for (Thread thread : threads) {
thread.start();
}
}
}
class ShareVariableRunnable implements Runnable {
private int count = 5;
public void run() {
System.out.println("" + Thread.currentThread().getName() + ",count:" + count--);
}
}
从上图结果可以看出,count变量是共享的,不然都会打印5。但是也发现了一点thread:1 与 thread:2 打印值一样,该现象就是我们通常称为的脏数据【多线程对同一变量进行读写操作不同步产生】。
解决方案在访问变量方法中增加synchronized关键字:
class ShareVariableRunnable implements Runnable {
private int count = 5;
public synchronized void run() {
System.out.println("" + Thread.currentThread().getName() + ",count:" + count--);
}
}
如图每次打印count都是正常递减,这里解释一下synchronized
关键字,含有synchronized
关键字的这个方法称为“互斥区” 或“临界区”,只有获得这个关键字对应的锁才能执行方法体,方法体执行完自动会释放锁。
停止线程
终止正在运行的线程方法有三种:
1. 使用退出标志,使线程正常的执行完run方法终止
2. 使用interrupt方法,使线程异常,线程进行捕获或抛异常,正常执行完run方法终止
3. 使用stop方法强制退出
这里主要说明前两种方法;
使用退出标志位
public class ThreadVariableStopDemo { public static void main(String[] args) throws InterruptedException { VariableStopThread thread = new VariableStopThread("thread_1"); thread.start(); Thread.sleep(1); thread.Stop(); } } class VariableStopThread extends Thread { private boolean interrupt = true; public VariableStopThread(String name) { super(name); } public void run() { System.out.println(Thread.currentThread().getName() + ":线程开始运行!"); int i = 0; while(interrupt) { System.out.println("" + (i++)); } System.out.println("我停止了! timer:" + System.currentTimeMillis()); } public void Stop() { System.out.println(Thread.currentThread().getName() + ":线程设置了停止! timer:" + System.currentTimeMillis()); this.interrupt = false; } }
使用interrupt方法
public class ThreadInterruptDemo { public static void main(String[] args) throws InterruptedException { Thread thread = new InterruptThread("thread_1"); thread.start(); Thread.sleep(1); System.out.println(thread.getName() + "线程设置:interrupt"); thread.interrupt(); } } class InterruptThread extends Thread { public InterruptThread(String name) { super(name); } @Override public void run() { System.out.println(Thread.currentThread().getName() + "线程开始!"); for(int i =0; i < 1000; i++) { try { Thread.sleep(0); System.out.println("" + (i + 1)); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!"); break; } } System.out.println(Thread.currentThread().getName() + "线程结束!"); } }
线程优先级
线程优先级范围为1-10,API提供等级分为:低(MIN_PRIORITY = 1),中(NORM_PRIORITY=5),高(MAX_PRIORITY=10)。
线程优先级有以下特点:
继承特性【线程A中启动线程B,线程B继承了A的优先级】
随机性【线程调度的顺序不一定是根据优先级,具有随机性】
public class ThreadPriorityDemo { public static void main(String[] args) { Thread thread = new ThreadPriority("thread_1<<<<"); Thread thread_1 = new ThreadPriority(">>>thread_2"); thread_1.setPriority(Thread.MIN_PRIORITY); //<设置线程优先级 thread.setPriority(Thread.MAX_PRIORITY); thread_1.start(); thread.start(); } } class ThreadPriority extends Thread { public ThreadPriority(String name) { super(name); } @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("" + Thread.currentThread().getName() + ",number:" + i + ",Priority:" + Thread.currentThread().getPriority()); } } }
守护线程
守护线程顾名思义是一个线程守护另一个线程【此线程为非守护线程】,故守护的线程称为守护线程,被守护的线程称为非守护线程。作用是为其他线程运行提供便利服务。
public class DaemonThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new DaemonThread();
thread.setDaemon(true);//设置线程为守护线程
thread.start();
System.out.println("" + Thread.currentThread().getName() + "停止运行!" );
}
}
class DaemonThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("DaemonThread 正在运行!");
}
}
}
从上图可以看出,主线程停止DaemonThread线程也相应的停止了,但不是立即停止。
线程让步
线程让步yield()
让当前线程释放CPU资源,让其他线程抢占。
public class ThreadYieldDemo {
public static void main(String[] args) {
Thread thread = new ThreadYield();
thread.start();
}
}
class ThreadYield extends Thread {
@Override
public void run() {
long time_start = System.currentTimeMillis();
for(int i = 0; i < 500000; i++) {
Thread.yield();
}
long time_end = System.currentTimeMillis();
System.out.println("用时:" + (time_end - time_start));
}
}