原创Java多线程详解(一)
只看书不实践是不行的。来实践1下~~~~~~(援用请指明来源)
先看看百科对多线程的介绍 http://baike.baidu.com/view/65706.htm?fr=aladdin
Java对多线程的支持 Java创建多线程的3种经常使用方法: 1)继承Thread类 重写Thread类的run方法,创建Thread子类实例,启动线程。 例如: /*
* @author wxismeit@163.com wangxu
*/
public class TreadOfextends extends Thread{
private int i;
//重写run()方法
public void run(){
for(i=0; i<50; i++){
System.out.println(getName() + " " + i);
//继承Thread类时直接使用this便可获得当前线程
}
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
for(int i=0; i<50; i++){
if(i == 10){
//直接通过创建类对象来调用start()方法
new TreadOfextends().start();
new TreadOfextends().start();
}
}
}
}
2)实现Runnable接口 重写run()方法,创建Runnable实例作为Thread的target。 例如: public class ThreadOfRun implements Runnable {
private int i;
//实现Runnable接口中的run()方法
public void run() {
for(i=0; i<50; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
//通过实现接口来实现多线程 就不能通过this关键字来获得当前进程
}
}
public static void main(String[] args) {
for(int i=0; i<50; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if(i == 10) {
ThreadOfRun tor = new ThreadOfRun();
//此处需要通过Thread的构造方法来new线程
new Thread(tor,"线程1").start();
new Thread(tor,"线程2").start();
}
}
}
}
使用FutureTask对象作为Thread的对象的target创建并启动新线程 import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class ThreadOfCallble implements Callable<Integer> {
//支持泛型
public Integer call() throws Exception {
int i;
for(i=0; i<50; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;//有返回值
}
public static void main(String[] args) {
//创建Callable对象
ThreadOfCallble toc = new ThreadOfCallble();
//通过FutureTask来包装Callable对象
FutureTask<Integer> ft = new FutureTask<Integer>(toc);
for(int i=0; i<50; i++) {
if(i ==10) {
new Thread(ft,"NewThread").start();
}
}
try {
//得到新线程的返回值
System.out.println("子线程的返回值 : " + ft.get());
}catch(Exception e) {
e.printStackTrace();
}
}
}
线程的生命周期 : 新建和就绪状态 ――>运行和阻塞状态――>线程死亡(不可复活)。 如图:(看不到请拖动图片)
join线程 当在某个程序履行中调用其他线程的join方法时,条用线程将被阻塞,直至被join线程履行完为止。 <pre class="java" name="code">public class ThreadOfjoin extends Thread {
public ThreadOfjoin(String name) {
super(name);
}
public void run() {
for(int i=0; i<50; i++) {
System.out.println(getName());
}
}
public static void main(String[] args) {
new ThreadOfjoin("NewThread").start();
for(int i=0; i<50; i++) {
if(i == 10) {
ThreadOfjoin toj = new ThreadOfjoin("JoinedThread");
toj.start();
try {
toj.join();//主线程调用了toj的join方法,需要等toj履行完主线程才能履行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName());
}
}
}
未完待续 : 线程优先级,线程同步,互斥锁,同步锁,死锁,线程通讯。 评论区留下Email可以取得《Java多线程设计模式》PDF版(通过网络爬虫小程序 自动匹配抓取你的Email并自动发送给你)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |