在java中实现多线程的方式有两种分别是继承Thread类和实现Runnable接口
1、继承Thread类
先来看看Thread类的结构
public class Thread implements Runnable
thread类实现了runnable接口,他们之间具有多态的关系。使用这种方式创建多线程最大的局限是java不支持多继承,所以大多数情况下使用实现runnable接口来创建多线程。
先看一个代码示例
package com.lut.thread1;
public class MyThread extends Thread {
public void run() {
System.out.println("mythread");
}
public static void main(String[] args) {
MyThread m=new MyThread();
m.start();
System.out.println("end");
}
}
从运行的结果看,在使用多线程时运行结果与代码的执行顺序无关。线程是一个子任务,cpu以不定的的方式或者以随机的方式来调用线程里的run方法。为了演示线程的随机性,在创建一个类
package com.lut.thread1;
public class RandomThread extends Thread{
public void run() {
try {
for(int i=0;i<10;i++) {
int time=(int)(Math.random()*1000);
Thread.sleep(time);
System.out.println("当前运行线程"+Thread.currentThread().getName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
RandomThread rd=new RandomThread();
rd.setName("mythread");
rd.start();
try {
for(int i=0;i<9;i++) {
int time=(int)(Math.random()*1000);
Thread.sleep(time);
System.out.println("主线程"+Thread.currentThread().getName());
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
运行结果
主线程main
当前运行线程mythread
主线程main
主线程main
当前运行线程mythread
当前运行线程mythread
主线程main
主线程main
主线程main
当前运行线程mythread
当前运行线程mythread
主线程main
当前运行线程mythread
主线程main
当前运行线程mythread
主线程main
当前运行线程mythread
当前运行线程mythread
当前运行线程mythread
在代码中为了使线程具有随机运行的效果,使用了随机数的形式,让线程处于挂起的状态,cpu的执行顺序具有不确定性。
2、实现runnable接口
由于java是单根继承,不支持多继承,因此我们可以通过实现runnable接口来创建多线程。
在Thread类中,其中两个构造函数Thread(Runnable target)和Thread(Runnable target,String name)说明他的构造函数支持是传入了runnable接口的对象。因此我们可以将实现了runnable接口的对象传入到Thread类中来创建多线程。
3、线程基本API
a、currentThread()返回当前被调用线程的基本信息。
package com.lut.thread1;
public class CurrentThread {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
}运行结果 main
b、isAlive方法是判断线程是否处于活动状态,所谓活动状态就是指线程已经启动尚未终止,线程处于正在运行或者准备运行的状态,称它为存活的。
package com.lut.thread1;
public class IsLive extends Thread{
public void run() {
System.out.println("run"+this.isAlive());
}
public static void main(String[] args) {
IsLive is=new IsLive();
System.out.println("beging"+is.isAlive());
is.start();
System.out.println("end"+is.isAlive());
}
}
运行结果
begingfalse
endtrue
runtrue
c、sleep方法
sleep方法是指当前正在运行的线程,在一定的时间内休眠(暂停),正在运行的线程指this.cuurentThread()返回的线程。
package com.lut.thread1;
public class SleepThread extends Thread {
public void run() {
try {
System.out.println("run =" + this.currentThread().getName() + " begin time=" + System.currentTimeMillis());
Thread.sleep(1000);
System.out.println("run =" + this.currentThread().getName() + " end time" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepThread st=new SleepThread();
st.setName("A");
System.out.println("begin"+System.currentTimeMillis());
st.start();
System.out.println("end"+System.currentTimeMillis());
}
}
运行结果
begin1530755334456
end1530755334457
run =A begin time=1530755334457
run =A end time1530755335458
d、getId()返回线程的唯一标识
3、停止线程
停止线程是比较重要的技术点,掌握这个方法可以对停止线程进行有效的处理。 有三种方法可以停止线程。
a、使用退出标志,当run方法运行结束,也就是正常退出。
b、使用stop方法,不推荐,因为这个方法不安全,被废弃了。
c、使用interrut方法中断线程。
在停止线程之前,我们先看判断线程的状态是不是停止的,java提供了两个方法。
this.interrupted()判断当前线程是否中断
this.isInterrupted()判断线程是否中断
api文档对interrupted()做了如下的解释interrupted具有测试当前线程是否中断,线程的状态由该方法清除。也就是说连续两次调用该方法,会改变当前线程的状态。
package com.lut.thread1;
public class StopThread extends Thread{
public void run() {
for(int i=0;i<10;i++) {
System.out.println(this.currentThread().getName()+"="+i);
}
System.out.println("当前线程是否停止"+this.currentThread().getName()+this.currentThread().interrupted());
}
public static void main(String[] args) throws InterruptedException {
StopThread st=new StopThread();
st.setName("A");
st.start();
st.sleep(1000);
st.interrupt();
Thread.currentThread().interrupt();
System.out.println("当前线程是否停止1"+Thread.currentThread().getName()+Thread.interrupted());
System.out.println("当前线程是否停止1"+Thread.currentThread().getName()+Thread.interrupted());
}
}
运行结果:A=0
A=1
A=2
A=3
A=4
A=5
A=6
A=7
A=8
A=9
当前线程是否停止Afalse
当前线程是否停止1maintrue
当前线程是否停止1mainfalse
从结果来看我们创建的线程虽然调用了interrupt()方法,但是并没有真正的停止线程。
最后来看两个方法的解释
this.interrupted()测试当前线程的是否是中断状态,执行后将状态标志清除false。
this.isInterrupted()测试Thread对象是否已经是中断状态,但不清除状态。
知道了这些我们来看看如何真正的停止线程呢
a、异常法,通过for语句package com.lut.thread1;
public class StopThread1 extends Thread{
public void run() {
for(int i=0;i<500000;i++) {
if(this.interrupted()) {
System.out.println(this.interrupted());
System.out.println("线程被终止了");
break;
}
System.out.println("i"+"="+i);
}
}
public static void main(String[] args) throws InterruptedException {
StopThread1 st=new StopThread1();
st.start();
st.sleep(2000);
st.setName("A");
st.interrupt();
System.out.println("end");
//System.out.println(st.interrupted());
}
}
运行结果:只截取了部分结果
i=258153
i=258154
i=258155
end
false
线程被终止了
b、在沉睡中停止
package com.lut.thread1;
public class StopThread2 extends Thread{
public void run() {
try {
System.out.println("run begin");
Thread.sleep(20000);
System.out.println("run end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("在沉睡中停止进入catch"+this.interrupted());
e.printStackTrace();
}
}
public static void main(String[] args) {
StopThread2 st=new StopThread2();
st.start();
try {
st.sleep(1000);
st.interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("main catch");
e.printStackTrace();
}
}
}
运行结果
run begin
在沉睡中停止进入catchfalse
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.lut.thread1.StopThread2.run(StopThread2.java:8)
从结果来看,在sleep状态下,停止某一个线程,会进入catch语句,并且清除中断状态,使之变为false。
暴力停止(stop)就不说了。
c、使用return停止线程
package com.lut.thread1;
public class StopThread3 extends Thread{
public void run() {
while(true) {
if(this.isInterrupted()) {
System.out.println("线程停止了");
return;
}
System.out.println("time"+System.currentTimeMillis());
}
}
public static void main(String[] args) throws InterruptedException {
StopThread3 st=new StopThread3();
st.start();
st.sleep(1000);
st.interrupt();
}
}
部分运行结果
time1530761891556
time1530761891556
time1530761891556
线程停止了
不过还是建议抛异常的形式来停止线程,因为在catch块中,可以将线程向上抛,使线程停止事件得以传播。
4、暂停线程
暂停线程意味着线程还可以恢复,在java'中通过suspend暂停线程,通过resume恢复线程。在使用这两个方法时,如果使用不当,容易造成公共同步对象的独占,使的其他线程无法访问公共资源。在暂停线程的同时,会出现因线程的暂停导致数据不同步,容易产生脏数据。同时这两个方法也被废弃了。
5、yield方法
yield方法是放弃当前的cpu资源,让给其他线程占用cpu资源,但是放弃时间不确定,有可能刚刚啊放弃,立马获得cpu时间片。
package com.lut.thread1;
public class YieldThread extends Thread{
long beginTime=System.currentTimeMillis();
int count=0;
public void run() {
for(int i=0;i<500000;i++) {
count=i+1;
Thread.yield();
System.out.println(count);
}
long endTime=System.currentTimeMillis();
System.out.println(endTime-beginTime);
}
public static void main(String[] args) {
YieldThread yt=new YieldThread();
yt.start();
}
}
6、线程的优先级
在操作系统中,线程可以划分优先级,优先级高的获得cpu资源较多,也就是说cpu优先执行优先级高的线程。线程具有10个优先级,分别为1-10,最小的MIN_priority=1,
norm-priority=5;max-priority=10;
线程的优先级具有继承性,比如A继承B,则A和B的优先级一样。
7、守护线程
java线程中,有两种一种是用户线程,一种是守护线程。
守护线程,就死陪伴的意思,当进程中不存在非守护线程的时候,则守护线程自动销毁,最典型的守护线程就是垃圾回收线程。设置守护线程setDaemon(true);
注意:a、thread.setDaemon(true)必须在thread.start()之前,否则就会抛出一个异常。你不能把正在运行的线程设置为守护线程。
b、在守护线程中产生的线程也是守护线程
c、守护线程应该永远不去访问固有资源,如文件、数据库因为他在任何时候甚至在一个操作的中间发生中断。
package com.lut.thread1;
public class DaemonThread extends Thread {
int i = 0;
public void run() {
while (true) {
System.out.println("i=" + i);
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
DaemonThread dt = new DaemonThread();
dt.setDaemon(true);
dt.start();
Thread.sleep(5000);
}
}
运行结果
i=0
i=1
i=2
i=3
i=4
i=5
1、继承Thread类
先来看看Thread类的结构
public class Thread implements Runnable
thread类实现了runnable接口,他们之间具有多态的关系。使用这种方式创建多线程最大的局限是java不支持多继承,所以大多数情况下使用实现runnable接口来创建多线程。
先看一个代码示例
package com.lut.thread1;
public class MyThread extends Thread {
public void run() {
System.out.println("mythread");
}
public static void main(String[] args) {
MyThread m=new MyThread();
m.start();
System.out.println("end");
}
}
从运行的结果看,在使用多线程时运行结果与代码的执行顺序无关。线程是一个子任务,cpu以不定的的方式或者以随机的方式来调用线程里的run方法。为了演示线程的随机性,在创建一个类
package com.lut.thread1;
public class RandomThread extends Thread{
public void run() {
try {
for(int i=0;i<10;i++) {
int time=(int)(Math.random()*1000);
Thread.sleep(time);
System.out.println("当前运行线程"+Thread.currentThread().getName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
RandomThread rd=new RandomThread();
rd.setName("mythread");
rd.start();
try {
for(int i=0;i<9;i++) {
int time=(int)(Math.random()*1000);
Thread.sleep(time);
System.out.println("主线程"+Thread.currentThread().getName());
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
运行结果
主线程main
当前运行线程mythread
主线程main
主线程main
当前运行线程mythread
当前运行线程mythread
主线程main
主线程main
主线程main
当前运行线程mythread
当前运行线程mythread
主线程main
当前运行线程mythread
主线程main
当前运行线程mythread
主线程main
当前运行线程mythread
当前运行线程mythread
当前运行线程mythread
在代码中为了使线程具有随机运行的效果,使用了随机数的形式,让线程处于挂起的状态,cpu的执行顺序具有不确定性。
2、实现runnable接口
由于java是单根继承,不支持多继承,因此我们可以通过实现runnable接口来创建多线程。
在Thread类中,其中两个构造函数Thread(Runnable target)和Thread(Runnable target,String name)说明他的构造函数支持是传入了runnable接口的对象。因此我们可以将实现了runnable接口的对象传入到Thread类中来创建多线程。
3、线程基本API
a、currentThread()返回当前被调用线程的基本信息。
package com.lut.thread1;
public class CurrentThread {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
}运行结果 main
b、isAlive方法是判断线程是否处于活动状态,所谓活动状态就是指线程已经启动尚未终止,线程处于正在运行或者准备运行的状态,称它为存活的。
package com.lut.thread1;
public class IsLive extends Thread{
public void run() {
System.out.println("run"+this.isAlive());
}
public static void main(String[] args) {
IsLive is=new IsLive();
System.out.println("beging"+is.isAlive());
is.start();
System.out.println("end"+is.isAlive());
}
}
运行结果
begingfalse
endtrue
runtrue
c、sleep方法
sleep方法是指当前正在运行的线程,在一定的时间内休眠(暂停),正在运行的线程指this.cuurentThread()返回的线程。
package com.lut.thread1;
public class SleepThread extends Thread {
public void run() {
try {
System.out.println("run =" + this.currentThread().getName() + " begin time=" + System.currentTimeMillis());
Thread.sleep(1000);
System.out.println("run =" + this.currentThread().getName() + " end time" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepThread st=new SleepThread();
st.setName("A");
System.out.println("begin"+System.currentTimeMillis());
st.start();
System.out.println("end"+System.currentTimeMillis());
}
}
运行结果
begin1530755334456
end1530755334457
run =A begin time=1530755334457
run =A end time1530755335458
d、getId()返回线程的唯一标识
3、停止线程
停止线程是比较重要的技术点,掌握这个方法可以对停止线程进行有效的处理。 有三种方法可以停止线程。
a、使用退出标志,当run方法运行结束,也就是正常退出。
b、使用stop方法,不推荐,因为这个方法不安全,被废弃了。
c、使用interrut方法中断线程。
在停止线程之前,我们先看判断线程的状态是不是停止的,java提供了两个方法。
this.interrupted()判断当前线程是否中断
this.isInterrupted()判断线程是否中断
api文档对interrupted()做了如下的解释interrupted具有测试当前线程是否中断,线程的状态由该方法清除。也就是说连续两次调用该方法,会改变当前线程的状态。
package com.lut.thread1;
public class StopThread extends Thread{
public void run() {
for(int i=0;i<10;i++) {
System.out.println(this.currentThread().getName()+"="+i);
}
System.out.println("当前线程是否停止"+this.currentThread().getName()+this.currentThread().interrupted());
}
public static void main(String[] args) throws InterruptedException {
StopThread st=new StopThread();
st.setName("A");
st.start();
st.sleep(1000);
st.interrupt();
Thread.currentThread().interrupt();
System.out.println("当前线程是否停止1"+Thread.currentThread().getName()+Thread.interrupted());
System.out.println("当前线程是否停止1"+Thread.currentThread().getName()+Thread.interrupted());
}
}
运行结果:A=0
A=1
A=2
A=3
A=4
A=5
A=6
A=7
A=8
A=9
当前线程是否停止Afalse
当前线程是否停止1maintrue
当前线程是否停止1mainfalse
从结果来看我们创建的线程虽然调用了interrupt()方法,但是并没有真正的停止线程。
最后来看两个方法的解释
this.interrupted()测试当前线程的是否是中断状态,执行后将状态标志清除false。
this.isInterrupted()测试Thread对象是否已经是中断状态,但不清除状态。
知道了这些我们来看看如何真正的停止线程呢
a、异常法,通过for语句package com.lut.thread1;
public class StopThread1 extends Thread{
public void run() {
for(int i=0;i<500000;i++) {
if(this.interrupted()) {
System.out.println(this.interrupted());
System.out.println("线程被终止了");
break;
}
System.out.println("i"+"="+i);
}
}
public static void main(String[] args) throws InterruptedException {
StopThread1 st=new StopThread1();
st.start();
st.sleep(2000);
st.setName("A");
st.interrupt();
System.out.println("end");
//System.out.println(st.interrupted());
}
}
运行结果:只截取了部分结果
i=258153
i=258154
i=258155
end
false
线程被终止了
b、在沉睡中停止
package com.lut.thread1;
public class StopThread2 extends Thread{
public void run() {
try {
System.out.println("run begin");
Thread.sleep(20000);
System.out.println("run end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("在沉睡中停止进入catch"+this.interrupted());
e.printStackTrace();
}
}
public static void main(String[] args) {
StopThread2 st=new StopThread2();
st.start();
try {
st.sleep(1000);
st.interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("main catch");
e.printStackTrace();
}
}
}
运行结果
run begin
在沉睡中停止进入catchfalse
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.lut.thread1.StopThread2.run(StopThread2.java:8)
从结果来看,在sleep状态下,停止某一个线程,会进入catch语句,并且清除中断状态,使之变为false。
暴力停止(stop)就不说了。
c、使用return停止线程
package com.lut.thread1;
public class StopThread3 extends Thread{
public void run() {
while(true) {
if(this.isInterrupted()) {
System.out.println("线程停止了");
return;
}
System.out.println("time"+System.currentTimeMillis());
}
}
public static void main(String[] args) throws InterruptedException {
StopThread3 st=new StopThread3();
st.start();
st.sleep(1000);
st.interrupt();
}
}
部分运行结果
time1530761891556
time1530761891556
time1530761891556
线程停止了
不过还是建议抛异常的形式来停止线程,因为在catch块中,可以将线程向上抛,使线程停止事件得以传播。
4、暂停线程
暂停线程意味着线程还可以恢复,在java'中通过suspend暂停线程,通过resume恢复线程。在使用这两个方法时,如果使用不当,容易造成公共同步对象的独占,使的其他线程无法访问公共资源。在暂停线程的同时,会出现因线程的暂停导致数据不同步,容易产生脏数据。同时这两个方法也被废弃了。
5、yield方法
yield方法是放弃当前的cpu资源,让给其他线程占用cpu资源,但是放弃时间不确定,有可能刚刚啊放弃,立马获得cpu时间片。
package com.lut.thread1;
public class YieldThread extends Thread{
long beginTime=System.currentTimeMillis();
int count=0;
public void run() {
for(int i=0;i<500000;i++) {
count=i+1;
Thread.yield();
System.out.println(count);
}
long endTime=System.currentTimeMillis();
System.out.println(endTime-beginTime);
}
public static void main(String[] args) {
YieldThread yt=new YieldThread();
yt.start();
}
}
6、线程的优先级
在操作系统中,线程可以划分优先级,优先级高的获得cpu资源较多,也就是说cpu优先执行优先级高的线程。线程具有10个优先级,分别为1-10,最小的MIN_priority=1,
norm-priority=5;max-priority=10;
线程的优先级具有继承性,比如A继承B,则A和B的优先级一样。
7、守护线程
java线程中,有两种一种是用户线程,一种是守护线程。
守护线程,就死陪伴的意思,当进程中不存在非守护线程的时候,则守护线程自动销毁,最典型的守护线程就是垃圾回收线程。设置守护线程setDaemon(true);
注意:a、thread.setDaemon(true)必须在thread.start()之前,否则就会抛出一个异常。你不能把正在运行的线程设置为守护线程。
b、在守护线程中产生的线程也是守护线程
c、守护线程应该永远不去访问固有资源,如文件、数据库因为他在任何时候甚至在一个操作的中间发生中断。
package com.lut.thread1;
public class DaemonThread extends Thread {
int i = 0;
public void run() {
while (true) {
System.out.println("i=" + i);
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
DaemonThread dt = new DaemonThread();
dt.setDaemon(true);
dt.start();
Thread.sleep(5000);
}
}
运行结果
i=0
i=1
i=2
i=3
i=4
i=5