欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java多线程详细总结

程序员文章站 2023-12-18 21:24:34
一、thread.start()与thread.run()的区别 通过调用thread类的start()方法来启动一个线程,这时此线程是处于就绪状态,并没有运行。然后通过...

一、thread.start()与thread.run()的区别

通过调用thread类的start()方法来启动一个线程,这时此线程是处于就绪状态,并没有运行。然后通过此thread类调用方法run()来完成其运行操作的,这里方法run()称为线程体,它包含了要执行的这个线程的内容,run方法运行结束,此线程终止,而cpu再运行其它线程。

而如果直接用run方法,这只是调用一个方法而已,程序中依然只有“主线程”这一个线程,并没有开辟新线程,其程序执行路径还是只有一条,这样就没有达到写线程的目的。

测试代码如下

复制代码 代码如下:

public class mythread implements runnable {
public void run() {
system.err.println(thread.currentthread().getname());
}
public static void main(string[] args) {
mythread thread = new mythread();
thread t1 = new thread(thread, "thread-1");
thread t2 = new thread(thread, "thread-2");
t1.run();
t2.run();
}
}

输出结果为

>>当前进程为:main

>>当前进程为:main

改为用start方法:

复制代码 代码如下:

package thread;
public class mythread implements runnable {
public void run() {
system.err.println(">>当前进程为:"+thread.currentthread().getname());
}
public static void main(string[] args) {
mythread thread = new mythread();
thread t1 = new thread(thread, "thread-1");
thread t2 = new thread(thread, "thread-2");
t1.start();
t2.start();
}
}

结果为:

>>当前进程为:thread-1

>>当前进程为:thread-2

二、threadlocal类详解

threadlocal很容易让人望文生义,想当然地认为是一个“本地线程”。其实,threadlocal并不是一个thread,而是thread的局部变量,也许把它命名为threadlocalvariable更容易让人理解一些。当使用threadlocal维护变量时,threadlocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

下面是线程局部变量(threadlocal variables)的关键点:

一个线程局部变量(threadlocal variables)为每个线程方便地提供了一个单独的变量。在多个线程操作该变量时候能够互不影响,因为每个线程操作的实际上是改变量的副本。threadlocal实例通常作为静态的私有的(private static)字段出现在一个类中,这个类用来关联线程。当多个线程访问threadlocal实例时,每个线程维护threadlocal提供的独立的变量副本。

下面是测试代码,用于测试:作用于一个对象上面的三个线程来操作同一个threadloacl对象(integer 类型),看是否会出现脏读等现象:

复制代码 代码如下:

public class test implements runnable {
private static threadlocal<integer> num = new threadlocal<integer>();
public void run() {
num.set(0);
for (int i = 0; i < 3; i++) {
num.set(num.get() + 1);
system.out.println(thread.currentthread().getname() + ":num="
+ num.get());
}
}
public static void main(string[] args) {
test test = new test();
thread t1 = new thread(test, "thread-1");
thread t2 = new thread(test, "thread-2");
thread t3 = new thread(test, "thread-3");
t1.start();
t2.start();
t3.start();
}
}

运行结果如下:

thread-3:num=1
thread-2:num=1
thread-1:num=1
thread-2:num=2
thread-3:num=2
thread-2:num=3
thread-1:num=2
thread-1:num=3
thread-3:num=3

从上面可以看出,完全没有出现脏读等的现象,因此threadlocal线程安全。

常用的使用:当dao类作为一个单例类时,数据库链接(connection)被每一个线程独立的维护,互不影响。

可以用来控制session的创建和使用,如下threadlocal<session> session = new threadlocal<session>();

threadloacal与同步机制的比较:

1、在同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量。这时该变量是多个线程共享的,使用同步机制要求程序慎密地分析什么时候对变量进行读写,什么时候需要锁定某个对象,什么时候释放对象锁等繁杂的问题,程序设计和编写难度相对较大。

2、而threadlocal则从另一个角度来解决多线程的并发访问。threadlocal会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突。因为每一个线程都拥有自己的变量副本,从而也就没有必要对该变量进行同步了。threadlocal提供了线程安全的共享对象,在编写多线程代码时,可以把不安全的变量封装进threadlocal。

3、概括起来说,对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而threadlocal采用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。

三、invalidmonitorstateexception异常

调用wait()/notify()/notifyall()中的任何一个方法时,如果当前线程没有获得该对象的锁,那么就会抛出illegalmonitorstateexception的异常(也就是说程序在没有执行对象的任何同步块或者同步方法时,仍然尝试调用wait()/notify()/notifyall()时)。由于该异常是runtimeexcpetion的子类,所以该异常不一定要捕获(尽管你可以捕获只要你愿意).作为runtimeexception,此类异常不会在wait(),notify(),notifyall()的方法签名提及。

如下代码,划线的部分会发生该异常,因为没有对该对象执行同步操作。

复制代码 代码如下:

public class common implements runnable {
public synchronized void method1() throws interruptedexception {
thread.sleep(1000);
system.out.println("method 1 called");
thread.sleep(1000);
system.out.println("method 1 done");
}
public synchronized void method2() throws interruptedexception {
thread.sleep(1000);
system.err.println("method 2 called");
thread.sleep(1000);
system.err.println("method 2 done");
}
public void run() {
system.out.println("running " + thread.currentthread().getname());
try {
if (thread.currentthread().getname().equals("thread-1")) {
this.wait(1000);
method1();
} else {
method2();
notifyall();
}
} catch (exception e) {
e.printstacktrace();
}
}
public static void main(string[] args) throws interruptedexception {
common c = new common();
thread t1 = new thread(c, "thread-1");
thread t2 = new thread(c, "thread-2");
t1.start();
t2.start();
}
}

改为一下代码,划线部分:
复制代码 代码如下:

public class common implements runnable {
public synchronized void method1() throws interruptedexception {
thread.sleep(1000);
system.out.println("method 1 called");
thread.sleep(1000);
system.out.println("method 1 done");
}
public synchronized void method2() throws interruptedexception {
thread.sleep(1000);
system.err.println("method 2 called");
thread.sleep(1000);
system.err.println("method 2 done");
}
public void run() {
system.out.println("running " + thread.currentthread().getname());
try {
if (thread.currentthread().getname().equals("thread-1")) {
synchronized(this){
this.wait(1000);
}
method1();
} else {
method2();
synchronized (this) {
notifyall();
}
}
} catch (exception e) {
e.printstacktrace();
}
}
public static void main(string[] args) throws interruptedexception {
common c = new common();
thread t1 = new thread(c, "thread-1");
thread t2 = new thread(c, "thread-2");
t1.start();
t2.start();
}
}

四、sleep()和wait()和suspend()的区别

区别一:

sleep是thread类的方法,是线程用来控制自身流程的,比如有一个要报时的线程,每一秒中打印出一个时间,那么我就需要在print方法前面加上一个sleep让自己每隔一秒执行一次。就像个闹钟一样。 sleep() 指示当前线程暂停执行指定时间,把执行机会让给其他线程,但是监控状态依然保持,到时后会自动恢复。调用sleep不会释放对象锁。

wait是object类的方法,用来线程间的通信,这个方法会使当前拥有该对象锁的线程等待,直到其他线程调用notify方法时再醒来,不过你也可以给它指定一个时间,自动醒来。这个方法主要是用在不同线程之间的调度。对象调用wait()方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyall)后本线程才进入对象锁定池准备获得对象锁进入运行状态。

区别二 :
 
调用wait方法会释放当前线程的锁,其实线程间的通信是靠对象来管理的,所有操作一个对象的线程是这个对象通过自己的wait方法来管理的。就好像这个对象是电视机,三个人是三个线程,那么电视机的遥控器就是这个锁,假如现在a拿着遥控器,电视机调用wait方法,那么a就交出自己的遥控器,由jvm虚拟机调度,遥控器该交给谁。

调用sleep方法不会释放锁,因为sleep()是一个线程用于管理自己的方法,不涉及线程通信。还是上面的例子,如果a拿遥控器的期间,他可以用自己的sleep每隔十分钟调一次台,而在他调台休息的十分钟期间,遥控器还在他的手上,其他人无法获得遥控器。

suspend() 方法容易发生死锁。调用suspend()的时候,目标线程会停下来,但却仍然持有在这之前获得的锁。此时,其他任何线程都不能访问锁定的资源,除非被"挂起"的线程恢复运行。对任何线程来说,如果它们想恢复目标线程,同时又试图使用任何一个锁定的资源,就会造成死锁

在以下情况下,持有锁的线程会释放锁:

1. 执行完同步代码块。

2. 在执行同步代码块的过程中,遇到异常而导致线程终止。

3. 在执行同步代码块的过程中,执行了锁所属对象的wait()方法,这个线程会释放锁,进行对象的等待池。

在以下情况下,线程虽然停止执行,但是线程不会释放锁:

1. 在执行同步代码块的过程中,执行了thread.sleep()方法,当前线程放弃cpu,开始睡眠,在睡眠中不会释放锁。

2. 在执行同步代码块的过程中,执行了thread.yield()方法,当前线程放弃cpu,但不会释放锁。

3. 在执行同步代码块的过程中,其他线程执行了当前对象的suspend()方法,当前线程被暂停,但不会释放锁。

五、在静态方法上使用同步

java只识别两种类型的锁:对象锁和类锁。

同步静态方法时会获取该类的"class”对象,所以当一个线程进入同步的静态方法中时,线程监视器获取类本身的锁,对整个类加锁,其它线程不能进入这个类的任何静态同步方法。它不像实例方法,因为多个线程可以同时访问不同实例同步实例方法。测试代码如下:

复制代码 代码如下:

public class common implements runnable {
public synchronized static void method1() throws interruptedexception {
thread.sleep(1000);
system.out.println("method 1 called");
thread.sleep(1000);
system.out.println("method 1 done");
}
public synchronized static void method2() throws interruptedexception {
thread.sleep(1000);
system.err.println("method 2 called");
thread.sleep(1000);
system.err.println("method 2 done");
}
public void run() {
system.out.println("running " + thread.currentthread().getname());
try {
if (thread.currentthread().getname().equals("thread-1")) {
method1();
} else {
method2();
// thread.currentthread().notify();
}
} catch (exception e) {
e.printstacktrace();
}
}
public static void main(string[] args) throws interruptedexception {
//以下代码创建了不同的对象上的不同线程,用来测试对于同一个类,会不会有锁
common c1 = new common();
common c2 = new common();
thread t1 = new thread(c1, "thread-1");
thread t2 = new thread(c2, "thread-2");
t1.start();
t2.start();
}
}

执行结果如下:
running thread-2
running thread-1
method 2 called
method 2 done
method 1 called
method 1 done

六、在一个对象上两个线程可以在同一时间分别调用两个不同的同步实例方法吗?

不能,因为一个对象已经同步了实例方法,线程获取了对象的对象锁。所以只有执行完该方法释放对象锁后才能执行其它同步方法。测试代码如下:

复制代码 代码如下:

public class common implements runnable {
public synchronized void method1() throws interruptedexception {
thread.sleep(1000);
system.out.println("method 1 called");
thread.sleep(1000);
system.out.println("method 1 done");
}
public synchronized void method2() throws interruptedexception {
thread.sleep(1000);
system.err.println("method 2 called");
thread.sleep(1000);
system.err.println("method 2 done");
}
public void run() {
system.out.println("running " + thread.currentthread().getname());
try {
if (thread.currentthread().getname().equals("thread-1")) {
method1();
} else {
method2();
// thread.currentthread().notify();
}
} catch (exception e) {
e.printstacktrace();
}
}
public static void main(string[] args) throws interruptedexception {
common c = new common();
thread t1 = new thread(c, "thread-1");
thread t2 = new thread(c, "thread-2");
t1.start();
t2.start();
//以下代码作为对比,创建不同的对象,则就不会受对象锁的干扰了
//common c1 = new common();
//common c2 = new common();
//c1.start();
//c2.start();
}
}

执行结果如下:
running thread-1
running thread-2
method 1 called
method 1 done
method 2 called
method 2 done

上一篇:

下一篇: