Java多线程核心技术(一):基础知识总结

概念

进程:进程是操作系统结构的基础,是一次程序的执行,是一个程序及其数据在处理机上顺序执行时所发生的活动,是程序在一个程序集合上运行的过程,它是系统进行资源分配和调度的一个基本单位。

线程:线程是进程中独立运行的子任务。使用多线程技术后,可以在同一时间运行更多不同种类的任务。

使用多线程

第一种方式:继承Thread类,并实现run方法

第二种方式:实现Runnable接口

注意:1、代码的运行结果与代码的顺序无关:线程是一个子任务,CPU以不确定的方式,或者说以随机的时间来调用线程中的run方法。

2、Thread.java类中的start()方法通知"线程规划器"此线程已经准备就绪,等待调用线程对象的run()方法。这个过程其实就是让系统安排一个时间来调用Thread中的run()方法,也就是使线程得到运行,启动线程,具有异步执行的效果,所以如果在程序中直接调用线程的run方法,那程序就是顺序执行的。


Thread类的结构:public class Thread implements Runnable

在Thread类的8个构造函数中,有两个构造函数Thread(Runnable target)和Thread(Runnable target,String name)可以传递Runnable接口,说明构造函数支持传入一个Runnable接口的对象。而Thread类实现了Runnable接口,所以完全可以将一个Thread对象作为Thread构造函数的参数传入,这样该Thread对象实现的run()方法就交由其他的线程进行调用。

共享数据

实现5个线程共同对一个count变量进行减法操作:

class MyThread extends Thread{
    public int count = 5;
    @Override
    public void run(){
    	super.run();
    	count--;
    	System.out.println("由 " + this.currentThread().getName() + "计算,count="+count);
    }
}
public class TestClass{
	public static void main(String[] args){
		MyThread mythread = new MyThread();
		Thread a = new Thread(mythread,"A");
		Thread b = new Thread(mythread,"B");
		Thread c = new Thread(mythread,"C");
		Thread d = new Thread(mythread,"D");
		Thread e = new Thread(mythread,"E");
		a.start();
		b.start();
		c.start();
		d.start();
		e.start();
	}
}
执行结果如下:


在JVM中,i--的操作分成如下3步:

(1)取得原有i值,

(2)计算i-1,

(3)对i进行赋值。

当五个线程同时进行操作i--时,其中的某个或某些线程在没执行完这三个步骤的情况下,其他的线程就插入进来了,就会造成结果的混乱。解决这个问题的方法是在润方法钱加synchronized关键字,保证run方法的原子性操作。synchronized可以在任意对象及方法上加锁,而加锁的这段代码称为”互斥区“或者”临界区“,当一个线程想执行同步方法里面的代码时,线程首先尝试去拿这把锁,如果能够拿到这把锁,那么这个线程就可以执行synchronized里面的代码。如果不能拿到这把锁,那么这个线程就会不断地尝试拿这把锁,直到能够拿到为止,而且是有多个线程同时去争抢这把锁。

currentThread()方法

currentThread()方法可返回代码段正在被哪个线程调用的信息。


当直接调用thread的run方法时,则run方法不是有其所在的线程去调用,而是由主线程去调用。

class MyThread extends Thread{
    public MyThread(){
    	System.out.println("构造函数开始");
    	System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
    	System.out.println("this.Name=" + this.getName());
    	System.out.println("构造函数结束");
    }
    @Override
    public void run(){
    	System.out.println("run方法开始");
    	System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
    	System.out.println("this.Name=" + this.getName());
    	System.out.println("run方法结束");
    }
}
    public class TestClass{
	public static void main(String[] args){
		MyThread mythread = new MyThread();
		Thread t = new Thread(mythread);
		t.setName("A");
		t.start();
	}
}


输出结果为:

构造函数开始
Thread.currentThread().getName()=main
this.Name=Thread-0
构造函数结束
run方法开始
Thread.currentThread().getName()=A
this.Name=Thread-0
run方法结束
在调用MyThread构造函数的线程是Main线程,而调用mythread的run方法的是名称为A的线程。


isAlive()方法

isAlive()方法的功能是判断当前线程是否处于活动状态,活动状态就是线程已经启动且尚未终止。线程处于正在运行或准备开始运行的状态,就认为线程是“存活”的。

class MyThread extends Thread{
    public MyThread(){
    	System.out.println("构造函数开始");
    	System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
    	System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive());
    	System.out.println("this.Name=" + this.getName());
    	System.out.println("this.isAlive()" + this.isAlive());
    	System.out.println("构造函数结束");
    }
    @Override
    public void run(){
    	System.out.println("run方法开始");
    	System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
    	System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive());
    	System.out.println("this.Name=" + this.getName());
    	System.out.println("this.isAlive()" + this.isAlive());
    	System.out.println("run方法结束");
    }
}
public class TestClass{
	public static void main(String[] args){
		MyThread mythread = new MyThread();
		Thread t = new Thread(mythread);
		t.setName("A");
		t.start();
	}
}
程序运行结果如下:

构造函数开始
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()=true
this.Name=Thread-0
this.isAlive()false
构造函数结束
run方法开始
Thread.currentThread().getName()=A
Thread.currentThread().isAlive()=true
this.Name=Thread-0
this.isAlive()false
run方法结束
这说明MyThread在构造函数中并没有存活,由于把MyThread的run方法交给了其他线程运行,所以在run方法中MyThread也不是存活的。

sleep()方法

sleep()方法的作用是在指定的毫秒数内让当前“正在执行的线程”休眠(暂停执行)。这个“正在执行的线程”是指this.currentThread()返回的线程。

class MyThread extends Thread{
    @Override
    public void run(){
    	try {
    		System.out.println("run threadName=" + this.currentThread().getName()+" begin="+System.currentTimeMillis());        	
			Thread.sleep(2000);
			System.out.println("run threadName=" + this.currentThread().getName()+" end  ="+System.currentTimeMillis());
		    
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
public class TestClass{
	public static void main(String[] args){
		MyThread mythread = new MyThread();
		System.out.println("begin="+System.currentTimeMillis());
		mythread.start();
		System.out.println("end  ="+System.currentTimeMillis());
	}
}
程序运行结果如下:

begin=1487766083887
end  =1487766083887
run threadName=Thread-0 begin=1487766083887
run threadName=Thread-0 end  =1487766085888
由于main线程与Mythread2线程是异步执行的,所以首先打印的信息为begin和end。而MyThread2线程是随后运行的,在最后两行打印run begin和run end相关的信息。

getId()方法

getId()方法的作用是取的线程的唯一标识

停止线程

在Java中有以下3种方法可以终止正在运行的线程:

(1)使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。

(2)使用stop方法强行终止线程,但是不推荐使用这种方法,因为stop方法和suspend及resume方法一样,都是作废过期的方法,使用它们可能会产生不可预料的结果。

如果使用stop方法强制让线程停止则有可能会使一下清理性的工作得不到完成。另一个情况就是对锁定的对象进行了“解锁”,导致数据得不到同步的处理,出现数据不一致的问题。

(3)使用interrupt方法中断线程,调用interrupt()方法仅仅是在当前线程中打了一个停止的标记,并不是真的停止线程。

判断线程是否是停止状态:

(1)this.interrupted():测试当前的线程是否已经中断,静态方法。线程的中断状态由该方法清除。所以,连续两次调用该方法,则第二次调用返回false(在第一次调用已经 清除了其中断状态之后,第二次调用检验完中断状态前,当前线程再次中断的情况除外)。

(2)this.isInterrupted():测试当前线程是否已经中断,非静态方法,并不会清除状态标志。

public class TestClass{
	public static void main(String[] args){
		
		try {
			MyThread mythread = new MyThread();
			mythread.start();
			Thread.sleep(1000);
			mythread.interrupt();
			System.out.println("当前线程是否停止? = "+Thread.interrupted());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
程序运行输出
当前线程是否停止? = false

这是因为mythread线程终止了,但是main线程一直在运行,这个“当前线程”就是main,所以打印了false。

在沉睡中停止

如果在线程的sleep()状态下停止线程,会抛出java.lang.InterruptedException异常,并且清除停止状态值,使之变成false。先中断线程在调用sleep()方法,结果是一样的。

暂停线程

暂停线程意味着此线程还可以恢复运行。在Java多线程中,可以使用suspend()方法暂停线程,使用resume()方法恢复线程的执行。

在suspend与resume方法时,如果使用不当,极易造成公共的同步对象的独占,是的其他线程无法访问公共同步对象。

class MyThread extends Thread{
	private long i = 0;
    @Override
    public void run(){
    	while(true){
    		i++;
    	}
    }
}
public class TestClass{
	public static void main(String[] args){
		
		try {
			MyThread mythread = new MyThread();
			mythread.start();
			Thread.sleep(1000);
			mythread.suspend();
			System.out.println("main end!");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
程序会打印出main end,但是将MyThread改为如下的写法,运行程序,控制台将不打印main end,这是因为当程序运行到println()方法内部停止时,同步锁未被释放。方法println()源代码如下所示:

public void println(long x){
    synchronized(this){
        print(x);
        newLine();
    }
}

yield方法

yield方法的作用是放弃当前的CPU资源,将它让给其他的任务去占用CPU执行时间。但放弃的时间不确定,有可能刚刚放弃,马上又获得CPU时间片。

class MyThread extends Thread{
    @Override
    public void run(){
    	long beginTime = System.currentTimeMillis();
    	int count = 0;
    	for(int i = 0; i < 50000000; i++){
    		//Thread.yield();
    		count += i;
    	}
    	long  endTime = System.currentTimeMillis();
    	System.out.println("用时:"+(endTime - beginTime) + "毫秒!");
    }
}
public class TestClass{
	public static void main(String[] args){
		MyThread thread = new MyThread();
		thread.start();		
	}
}
正常情况下执行时间用了3毫秒,把//Thread.yield()的注释去掉,用时3189毫秒!

线程的优先级

优先级较高的线程得到的CPU资源较多,也就是CPU优先执行优先级较高的线程对象中的任务。设置线程的优先级使用setPriority(int newPriority)方法。在Java中,线程的优先级分为1~10这10个等级,如果小于1或大于10,则JDK抛出异常throw new IllegalArgumentException()。

JDK中使用3个常量来预置定义优先级的值,代码如下:

public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
在Java中,线程的优先级具有继承性,比如A线程启动B线程,则B线程的优先级与A是一样的。下面是代码实现的例子:

class MyThread1 extends Thread{
    @Override
    public void run(){
    	System.out.println("MyThread1 run priority="+this.getPriority());
    	MyThread2 thread2 = new MyThread2();
    	thread2.start();
    }
}
class MyThread2 extends Thread{
    @Override
    public void run(){
    	System.out.println("MyThread2 run priority="+this.getPriority());
    }
}
public class TestClass{
	public static void main(String[] args){
		System.out.println("main thread begin priority="+Thread.currentThread().getPriority());
		Thread.currentThread().setPriority(6);
		System.out.println("main thread begin priority="+Thread.currentThread().getPriority());
	    MyThread1 thread1 = new MyThread1();
	    thread1.start();
	}
}
程序运行结果为:

main thread begin priority=5
main thread begin priority=6
MyThread1 run priority=6
MyThread2 run priority=6

守护线程

在Java线程中有两种线程,一种是用户线程,另一种是守护线程。

守护线程是一种特殊的线程,它的特性有“陪伴”的含义,当进程中不存在非守护线程了,则守护线程自动销毁。典型的守护线程就是垃圾回收线程,当进程中没有非守护线程了,则垃圾回收线程也就没有存在的必要了,自动销毁。

class MyThread extends Thread{
    private int i = 0;
	@Override
    public void run(){   	
		try {
			while(true){
	    		i++;
	    		System.out.println("i="+i);
	    		Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
    }
}
public class TestClass{
	public static void main(String[] args){		
		try {
			MyThread thread = new MyThread();
			thread.setDaemon(true);
			thread.start();
			Thread.sleep(5000);
			System.out.println("我离开thread对象也不再打印了,也就是停止了!");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
如下是执行结果,当main线程执行完,守护线程MyThread就销毁了。

i=1
i=2
i=3
i=4
i=5
我离开thread对象也不再打印了,也就是停止了!




















  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值