一、扩展java.lang.Thread类
public class ThreadDemo1 {
public static void main(String[] args){
Demo d = new Demo();
d.start();
for(int i=0;i<60;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
class Demo extends Thread{
public void run(){
for(int i=0;i<60;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
二、实现java.lang.Runnable接口
public class ThreadDemo2 {
public static void main(String[] args){
Demo2 d =new Demo2();
Thread t = new Thread(d);
t.start();
for(int x=0;x<60;x++){
System.out.println(Thread.currentThread().getName()+x);
}
}
}
class Demo2 implements Runnable{
public void run(){
for(int x=0;x<60;x++){
System.out.println(Thread.currentThread().getName()+x);
}
}
}
三、Thread和Runnable的区别
如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。 总结:
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立
在java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。因为每当使用java命令执行一个类的时候,实际上都会启动 一个JVM,每一个jVM实习在就是在操作系统中启动了一个进程。四、线程状态转换
1、新建状态(New):新创建了一个线程对象。
2、就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法。该状态的线程位于可运行线程池中,变得可运行,等待获取CPU的使用权。
3、运行状态(Running):就绪状态的线程获取了CPU,执行程序代码。
4、阻塞状态(Blocked):阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:
(一)、等待阻塞:运行的线程执行wait()方法,JVM会把该线程放入等待池中。
(二)、同步阻塞:运行的线程在获取对象的同步锁时,若该同步锁被别的线程占用,则JVM会把该线程放入锁池中。
(三)、其他阻塞:运行的线程执行sleep()或join()方法,或者发出了I/O请求时,JVM会把该线程置为阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
5、死亡状态(Dead):线程执行完了或者因异常退出了run()方法,该线程结束生命周期。
线程的调度
1、调整线程优先级:Java线程有优先级,优先级高的线程会获得较多的运行机会。
Java线程的优先级用整数表示,取值范围是1~10,Thread类有以下三个静态常量:
static int MAX_PRIORITY
线程可以具有的最高优先级,取值为10。
static int MIN_PRIORITY
线程可以具有的最低优先级,取值为1。
static int NORM_PRIORITY
分配给线程的默认优先级,取值为5。
Thread类的setPriority()和getPriority()方法分别用来设置和获取线程的优先级。
每个线程都有默认的优先级。主线程的默认优先级为Thread.NORM_PRIORITY。
线程的优先级有继承关系,比如A线程中创建了B线程,那么B将和A具有相同的优先级。
JVM提供了10个线程优先级,但与常见的操作系统都不能很好的映射。如果希望程序能移植到各个操作系统中,应该仅仅使用Thread类有以下三个静态常量作为优先级,这样能保证同样的优先级采用了同样的调度方式。
2、线程睡眠:Thread.sleep(long millis)方法,使线程转到阻塞状态。millis参数设定睡眠的时间,以毫秒为单位。当睡眠结束后,就转为就绪(Runnable)状态。sleep()平台移植性好。
3、线程等待:Object类中的wait()方法,导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 唤醒方法。这个两个唤醒方法也是Object类中的方法,行为等价于调用 wait(0) 一样。
4、线程让步:Thread.yield() 方法,暂停当前正在执行的线程对象,把执行机会让给相同或者更高优先级的线程。
5、线程加入:join()方法,等待其他线程终止。在当前线程中调用另一个线程的join()方法,则当前线程转入阻塞状态,直到另一个进程运行结束,当前线程再由阻塞转为就绪状态。
6、线程唤醒:Object类中的notify()方法,唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。 直到当前的线程放弃此对象上的锁定,才能继续执行被唤醒的线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争;例如,唤醒的线程在作为锁定此对象的下一个线程方面没有可靠的特权或劣势。类似的方法还有一个notifyAll(),唤醒在此对象监视器上等待的所有线程。
线程类的一些常用方法:
sleep(): 强迫一个线程睡眠N毫秒。
isAlive(): 判断一个线程是否存活。
join(): 等待线程终止。
activeCount(): 程序中活跃的线程数。
enumerate(): 枚举程序中的线程。
currentThread(): 得到当前线程。
isDaemon(): 一个线程是否为守护线程。
setDaemon(): 设置一个线程为守护线程。(用户线程和守护线程的区别在于,是否等待主线程依赖于主线程结束而结束)
setName(): 为线程设置一个名称。
wait(): 强迫一个线程等待。
notify(): 通知一个线程继续运行。
setPriority(): 设置一个线程的优先级。
sleep(): 强迫一个线程睡眠N毫秒。
isAlive(): 判断一个线程是否存活。
join(): 等待线程终止。
activeCount(): 程序中活跃的线程数。
enumerate(): 枚举程序中的线程。
currentThread(): 得到当前线程。
isDaemon(): 一个线程是否为守护线程。
setDaemon(): 设置一个线程为守护线程。(用户线程和守护线程的区别在于,是否等待主线程依赖于主线程结束而结束)
setName(): 为线程设置一个名称。
wait(): 强迫一个线程等待。
notify(): 通知一个线程继续运行。
setPriority(): 设置一个线程的优先级。
五、线程同步
1. 把synchronized当作函数修饰符时,示例代码如下:
Public synchronized void methodAAA()
{
//….
}
2.同步块,示例代码如下:
public void method3(SomeObject so)
{
synchronized(so)
}
六、线程经典实例
1.生产消费
<span style="font-size:12px;color:#000099;">package www.Thread.study;
/*
class Resourse11{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name){
while(flag)
try {
wait();
} catch (InterruptedException e){}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
notifyAll();
flag=true;
}
public synchronized void out(){
while(!flag)
try {
wait();
} catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"..消费者......"+this.name);
notifyAll();
flag=false;
}
}
class Producer implements Runnable{
Resourse11 r;
Producer(Resourse11 r){
this.r=r;
}
public void run(){
int i=0;
while(true){
r.set("烤鸭");
}
}
}
class Coustomer implements Runnable{
Resourse11 r;
Coustomer(Resourse11 r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}
public class ProducerCoustomer {
public static void main(String[] args){
//创建资源
Resourse11 r=new Resourse11();
//创建任务
Producer t1=new Producer(r);
Coustomer t2=new Coustomer(r);
//创建线程,执行路径
Thread a1=new Thread(t1);
Thread a2=new Thread(t2);
Thread a3=new Thread(t1);
Thread a4=new Thread(t1);
//开启线程
a1.start();
a2.start();
a3.start();
a4.start();
}
}
*/
import java.util.concurrent.locks.*;
class Resourse11 {
private String name;
private int count = 1;
private boolean flag = false;
// 创建一个锁对象
Lock lock = new ReentrantLock();
// 通过已有锁获取该锁上的监视器对象
//Condition con = lock.newCondition();
Condition Producer_con = lock.newCondition();
Condition Customer_con = lock.newCondition();
public void set(String name) {
lock.lock();
try {
while (flag)
try {
Producer_con.await();
} catch (InterruptedException e) {
}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName() + "..生产者.."
+ this.name);
Customer_con.signalAll();
flag = true;
} finally {
lock.unlock();
}
}
public void out() {
lock.lock();
try {
while (!flag)
try {
Customer_con.await();
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + "..消费者......"+ this.name);
Producer_con.signalAll();
flag = false;
}
finally {
lock.unlock();
}
}
}
class Producer implements Runnable {
Resourse11 r;
Producer(Resourse11 r) {
this.r = r;
}
public void run() {
int i = 0;
while (true) {
r.set("烤鸭");
}
}
}
class Coustomer implements Runnable {
Resourse11 r;
Coustomer(Resourse11 r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class ProducerCoustomer {
public static void main(String[] args) {
// 创建资源
Resourse11 r = new Resourse11();
// 创建任务
Producer t1 = new Producer(r);
Coustomer t2 = new Coustomer(r);
// 创建线程,执行路径
Thread a1 = new Thread(t1);
Thread a2 = new Thread(t2);
Thread a3 = new Thread(t1);
Thread a4 = new Thread(t1);
// 开启线程
a1.start();
a2.start();
a3.start();
a4.start();
}
}</span>
package www.Thread.study;
/*
等待|唤醒机制
涉及的方式
1.wait():让线程处于冻结状态。被wait的线程会被存储到线程池中
2.notify();唤醒线程池中一个线程(任意)
3.notifyAll();唤醒线程池中所有线程
*/
class Resourse{
String name;
String sex;
}
class Input implements Runnable{
Resourse r;
Input(Resourse r){
this.r=r;
}
public void run(){
int i=0;
while(true){
synchronized(r){
if(i==0){
r.name="xiaoli";
r.sex="nan";
}else{
r.name="芊芊";
r.sex="女女女";
}
}
i=(i+1)%2;
}
}
}
class Output implements Runnable{
Resourse r;
Output(Resourse r){
this.r=r;
}
public void run(){
while(true){
synchronized(r){
System.out.println(r.name+"..."+r.sex);
}
}
}
}
public class Tongxin{
public static void main(String[] args){
//创建资源
Resourse r=new Resourse();
//创建任务
Input t1=new Input(r);
Output t2=new Output(r);
//创建线程,执行路径
Thread a1=new Thread(t1);
Thread a2=new Thread(t2);
//开启线程
a1.start();
a2.start();
}
}
//代码优化 详细看Dengdaihuanxing.java
-----------------------------------------------------
package www.Thread.study;
/*
等待|唤醒机制
涉及的方式
1.wait():让线程处于冻结态状。被atiw的线程会被存储到线程池中
2.notify();唤醒线程池中一个线程(任意)
3.notifyAll();唤醒线程池中所有线程
*/
class Resourse2{
<span style="white-space:pre"> </span>String name;
<span style="white-space:pre"> </span>String sex;
<span style="white-space:pre"> </span>boolean flag=false;
}
class Input2 implements Runnable{
<span style="white-space:pre"> </span>Resourse2 r;
<span style="white-space:pre"> </span>Input2(Resourse2 r){
<span style="white-space:pre"> </span>this.r=r;<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void run(){
<span style="white-space:pre"> </span>int i=0;
<span style="white-space:pre"> </span>while(true){
<span style="white-space:pre"> </span>synchronized(r){
<span style="white-space:pre"> </span>if(r.flag)
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>r.wait();
<span style="white-space:pre"> </span>} catch (InterruptedException e){}
<span style="white-space:pre"> </span>if(i==0){
<span style="white-space:pre"> </span>r.name="xiaoli";
<span style="white-space:pre"> </span>r.sex="nan";
<span style="white-space:pre"> </span>}else{
<span style="white-space:pre"> </span>r.name="芊芊";
<span style="white-space:pre"> </span>r.sex="女女女";
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>r.notify();
<span style="white-space:pre"> </span>r.flag=true;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>i=(i+1)%2;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
}
class Output2 implements Runnable{
<span style="white-space:pre"> </span>Resourse2 r;
<span style="white-space:pre"> </span>Output2(Resourse2 r){
<span style="white-space:pre"> </span>this.r=r;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void run(){
<span style="white-space:pre"> </span>while(true){
<span style="white-space:pre"> </span>synchronized(r){
<span style="white-space:pre"> </span>if(!r.flag)
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>r.wait();
<span style="white-space:pre"> </span>} catch (InterruptedException e) {}
<span style="white-space:pre"> </span>System.out.println(r.name+"..."+r.sex);<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>r.notify();
<span style="white-space:pre"> </span>r.flag=false;
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
}
public class Dengdaihuanxing{
<span style="white-space:pre"> </span>public static void main(String[] args){
<span style="white-space:pre"> </span>//创建资源
<span style="white-space:pre"> </span>Resourse2 r=new Resourse2();
<span style="white-space:pre"> </span>//创建任务
<span style="white-space:pre"> </span>Input2 t1=new Input2(r);
<span style="white-space:pre"> </span>Output2 t2=new Output2(r);
<span style="white-space:pre"> </span>//创建线程,执行路径
<span style="white-space:pre"> </span>Thread a1=new Thread(t1);
<span style="white-space:pre"> </span>Thread a2=new Thread(t2);
<span style="white-space:pre"> </span>//开启线程
<span style="white-space:pre"> </span>a1.start();
<span style="white-space:pre"> </span>a2.start();
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
}
/*
//代码优化
class Resourse1{
<span style="white-space:pre"> </span>private String name;
<span style="white-space:pre"> </span>private String sex;
<span style="white-space:pre"> </span>private boolean flag=false;
<span style="white-space:pre"> </span>public synchronized void set(String name,String sex){
<span style="white-space:pre"> </span>if(flag)
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>wait();
<span style="white-space:pre"> </span>} catch (InterruptedException e){}
<span style="white-space:pre"> </span>this.name=name;
<span style="white-space:pre"> </span>this.sex=sex;
<span style="white-space:pre"> </span>notify();
<span style="white-space:pre"> </span>flag=true;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public synchronized void out(){
<span style="white-space:pre"> </span>if(!flag)
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>wait();
<span style="white-space:pre"> </span>} catch (InterruptedException e){}
<span style="white-space:pre"> </span>System.out.println(name+"..+.."+sex);<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>notify();
<span style="white-space:pre"> </span>flag=false;<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
}
class Input1 implements Runnable{
<span style="white-space:pre"> </span>Resourse1 r;
<span style="white-space:pre"> </span>Input1(Resourse1 r){
<span style="white-space:pre"> </span>this.r=r;<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void run(){
<span style="white-space:pre"> </span>int i=0;
<span style="white-space:pre"> </span>while(true){<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>if(i==0){
<span style="white-space:pre"> </span>r.set("xiaoming","man");
<span style="white-space:pre"> </span>}else{
<span style="white-space:pre"> </span>r.set("芊芊", "女女女");<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>i=(i+1)%2;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
}
class Output1 implements Runnable{
<span style="white-space:pre"> </span>Resourse1 r;
<span style="white-space:pre"> </span>Output1(Resourse1 r){
<span style="white-space:pre"> </span>this.r=r;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void run(){
<span style="white-space:pre"> </span>while(true){<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>r.out();<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
}
public class Dengdaihuanxing{
<span style="white-space:pre"> </span>public static void main(String[] args){
<span style="white-space:pre"> </span>//创建资源
<span style="white-space:pre"> </span>Resourse1 r=new Resourse1();
<span style="white-space:pre"> </span>//创建任务
<span style="white-space:pre"> </span>Input1 t1=new Input1(r);
<span style="white-space:pre"> </span>Output1 t2=new Output1(r);
<span style="white-space:pre"> </span>//创建线程,执行路径
<span style="white-space:pre"> </span>Thread a1=new Thread(t1);
<span style="white-space:pre"> </span>Thread a2=new Thread(t2);
<span style="white-space:pre"> </span>//开启线程
<span style="white-space:pre"> </span>a1.start();
<span style="white-space:pre"> </span>a2.start();<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
}
*/