您的位置:首页 > 编程语言 > Java开发

java多线程分析

2015-06-21 17:45 483 查看
一、基本概念

1、什么是进程

进程是正在执行的程序,每一个进程都有一个执行顺序。当一个程序执行,操作系统将为为其分配资源。

2、什么是线程

线程是进程中的一个实体,是被系统独立调度和分派的基本单位。线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。JVM中,一个进至少有一个线程(不算垃圾回收线程)。

3、多线程存在的意义

(1)达到同时处理的效果,实际上是更好的抢夺CPU资源。

(2)一个线程可以为另一个线程服务,从操作系统角度而言,充分利用了CPU资源,用户角度而言,用户等待时间更少。

4、线程的创建方式

Java中,创建线程有两种方式

一种方法是将类声明为 Thread 的子类,并重写该子类的run方法,另一种方法是实现 Runnable 接口的类,并重写该子类的run方法。然后再调用线程实例的start()方法。调用start()方法时 ,JVM为我们做了两件事:启动线程,调用run()方法。

示例:创建线程的方式:声明为Thread的子类。

public class threadDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
thread.start();
for(int i = 0;i<1000;i++){
System.out.println("main---"+i);
}
}

}
class MyThread extends Thread{
public void run(){
for(int i= 0;i<1000;i++){
System.out.println("run()----"+i);
}
}
}


示例:实现Runanble接口

public class ThreadDemo1 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
new Thread(thread).start();
for(int i = 0;i<1000;i++){
System.out.println("main()---"+i);
}

}

}
class MyThread implements Runnable{
public void run(){
for(int i =0;i<1000;i++){
System.out.println("run()----"+i);
}
}
}


结果可以看到main—和run—交替输出,并且每次结果都不同,说明结果具有随机性,主线程和子线程在“同时”运行时,每次获得的CPU调度具有随机性(在不改变线程优先级的情况下);

5、线程实例调用start()方法和run()方法的区别;

start:开启线程并执行该线程的run方法。

run:仅仅是对象的方法调用,而线程创建了,并没有运行。

6、线程生命周期

当new一个线程,实际上创建了一个线程,调用start方法后进入Runnable状态,即可以被调度运行状态,并没有真正开始运行,调度器可以将CPU分配给它,使线程进入Running状态,真正运行其中的程序代码。线程在运行过程中,有以下几个可能的去向:

(1)时间片轮转结束,这个线程又变为Runnable状态,等待处理机调度。

(2)处理机将时间片给了该线程,执行过程中没有遇到任何阻隔,也就是run()方法执行完毕。

(3)线程在执行过程中请求锁,却得不到,这时候它要进入lock pool中等待对象的锁,等到锁后又会进入Runnable状态,可以被调度运行。

(4)线程在执行过程中遇到wait()方法,它会被放入wait pool中等待,直到有notify()或interrupt()方法执行,它才会被唤醒或打断进入lock pool开始等待对象锁,等到锁后进入Runnable状态。

7、线程的的标识

自定义线程都有一个名称:Thread-编号,编号从0开始。

示例:

public class threadDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
MyThread thread1 = new MyThread();
thread.start();
thread1.start();
}
}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println(this.getName());
}
}
}


可以看到Thread-0和Thread-1输出。

如何给线程命名

public class threadDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread("thread");
MyThread thread1 = new MyThread("thread1");
thread.start();
thread1.start();
}
}
class MyThread extends Thread{
MyThread(String s){
super(s);
}
public void run(){
while(true){
System.out.println(this.getName());
}
}
}


查看API文档,Thread里面有个构造方法Thread(String name),MyThread继承Thread,重写了构造方法。

给线程命名的第二种方式,thread对象调用setName(),也能达到同样的效果。

示例:

public class threadDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
thread.setName("thread");
MyThread thread1 = new MyThread();
thread1.setName("thread1");
thread.start();
thread1.start();
}
}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println(this.getName());
}
}
}


看一个售票示例:有四个窗口同时售票,当然不能售出相同的票,这里可以在tickets类中定义一个静态的成员变量,被子线程所共享。售出的票将不会相同。

public class TicketDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ticket t1 = new ticket();
ticket t2 = new ticket();
ticket t3 = new ticket();
ticket t4 = new ticket();
t1.start();
t2.start();
t3.start();
t4.start();
}

}
class ticket extends Thread{
private static int tickets = 100;
boolean more = true;
public void run() {
while (more) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
}else {
more = false;
}
}
}
}


再来看用实现Runnable接口子类来实现多线程的例子。定义一个Runnable接口的子类对象。启动四个线程来同时调用子类的run方法,同样能够达到售票效果。不然看出,创建线程,关联实现Runnable接口的子类,并调用其run方法,能够实现资源的共享。

public class Runnabletest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
tickets t = new tickets();
Thread thread1 = new Thread(t);
Thread thread2 = new Thread(t);
Thread thread3 = new Thread(t);
Thread thread4 = new Thread(t);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}

}
class tickets implements Runnable{
private int tickets = 100;
boolean more = true;
public void run() {
while (more) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
}else {
more = false;
}
}
}

}


实现Runnable接口启动线程的好处:1、避免但继承的局限性(Java只支持单继承继承)2、能做到资源的共享。

两种方式的区别:

线程代码存放的位置不同:继承Thread :代码存放在Thread子类的run方法中;实现Runnable接口:代码存放在接口子类的run方法中。

二、Java多线程的安全问题

1、同步代码块解决java多线程中对共享代码块的访问(关键字synchronized)

上述的卖票程序会出现一个问题:当tickets为1时,thread0 的if (tickets > 0)判断结束后,下一个 thread执行,将ticket–.则thread0会卖出ticket为0的票。解决办法:在对共享数据操时,不可以被其他线程打断。下面的同步代码块解决了这一问题,不会出现卖负数票的情况。弊端:多了一步锁的判断消耗了资源。

示例:

public class TicketDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ticket t1 = new ticket();
ticket t2 = new ticket();
ticket t3 = new ticket();
ticket t4 = new ticket();
t1.start();
t2.start();
t3.start();
t4.start();
}

}
class ticket extends Thread{
private static int tickets = 100;
boolean more = true;
public void run() {
while (more) {
synchronized (new Object()) {
if (tickets > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
} else {
more = false;
}
}
}
}
}


2、同步函数(用synchronized修饰的函数)

示例:

public class SyschronizedTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Bank {
private int sum;
public void add(int n) {
try {
Thread.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sum += n;
System.out.println("sum=" + sum);
}

}
class Cus implements Runnable {
private Bank bank = new Bank();
public void run() {
for (int i = 0; i < 3; i++) {
bank.add(100);
}
}

}


以上程序在运行时会出现一个问题:Thread-0调用add方法, 执行完sum += n,假设此时sum值为100,之后,中断,Thread-1执行sum += n,此时sum值为200,Thread-0继续执行,打印结果为sum=200,出现了错误。为此我们加入了synchronized关键字来修饰add()方法,避免这一状况发生。

如下示例所示:

public class SyschronizedTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Bank {
private int sum;
public synchronized void add(int n) {
try {
Thread.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sum += n;
System.out.println("sum=" + sum);
}
}
class Cus implements Runnable {
private Bank bank = new Bank();
public void run() {
for (int i = 0; i < 3; i++) {
bank.add(100);
}
}

}


3、同步函数的锁是this指针。

验证一下:创建两个线程一个线程执行run方法中的同步代码块,另一个线程执行run方法中的同步函数。

示例:

public class TicketDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ticket t1 = new ticket();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t1);
thread1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.flag = false;
thread2.start();
}
}
class ticket implements Runnable{
private int tickets = 100;
boolean more = true;
boolean flag = true;
public void run() {
if (flag) {
while (more) {
synchronized (this) {
if (tickets > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
} else {
more = false;
}
}
}
}else{
show();
}
}
private synchronized void show(){
while (more) {
if (tickets > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
} else {
more = false;
}
}
}
}


将同步代码块中的锁换成this后,执行结果正常,由此可以说明:同步函数中使用的锁是this.

4、stactic修饰的同步函数的锁是该方法所在类的字节码文件对象。

下面来验证一下,将程序稍作修改

public class TicketDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ticket t1 = new ticket();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t1);
thread1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.flag = false;
thread2.start();
}
}
class ticket implements Runnable{
private static int tickets = 100;
static boolean  more = true;
boolean flag = true;
public void run() {
if (flag) {
while (more) {
synchronized (this) {
if (tickets > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
} else {
more = false;
}
}
}
}else{
show();
}
}
private  static synchronized  void show(){
while (more) {
if (tickets > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "...sale:" + tickets--);
} else {
more = false;
}
}
}
}


结果:

.................
Thread-0...sale:3
Thread-1...sale:2
Thread-0...sale:1
Thread-1...sale:0


出现了卖0票的情况,显然static 修饰的同步函数锁不是this,将this改成ticket.class后,程序正常,由此可以说名stactic修饰的同步函数的锁是该方法所在类的字节码文件对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: