在java中要想实现多线程,有两种手段,一种是继承Thread类,另外一种是实现Runable接口。
1、继承Thread类Demo:
public class PrimeThread extends Thread {
public static void main(String[] args) {
DemoThread demo = new DemoThread();
demo.start();
}
}
class DemoThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 400; i++) {
System.out.println("primeThread run ----- " + i);
}
}
}
2、实现Runable接口:
public class PrimeRun {
public static void main(String[] args) {
DemoRun demo = new DemoRun();
new Thread(demo).start();
}
}
class DemoRun implements Runnable {
@Override
public void run() {
for (int i = 0; i < 40; i++) {
System.out.println("PrimeRun run ----- " + i);
}
}
}
注:在上面的调用方法中,用的是start()方法,而不是run()方法,主要是因为start()方法中,会启动调用线程程序,并调用run()方法,而run()方法,只是线程主是工作内容,而没有开启线程。一个线程只能启动一次,如果该线程已经开启了,还调用start()方法来启动线程,则会抛出IllegalThreadStateException 异常。
Causes this thread to begin execution; the Java Virtual Machine calls the run() method of this thread. It is never legal to start a thread more than once. IllegalThreadStateException if the thread was already started.
两种方式的区别与联系:
1、避免点继承的局限,一个类可以继承多个接口。
2、适合于资源的共享
public class TicketThreadDemo {
public static void main(String[] args) {
TicketTread t1 = new TicketTread("售票员1");
TicketTread t2 = new TicketTread("售票员2");
TicketTread t3 = new TicketTread("售票员3");
TicketTread t4 = new TicketTread("售票员4");
t1.start(); //每个线程都各卖了20张,共卖了80张票
t2.start();//但实际只有20张票,每个线程都卖自己的票
t3.start();//没有达到资源共享
t4.start();//可以在tick上加static修饰,这样就可以让4个线程同时卖这100张票,但是static修饰的成员生命周期太长,所以尽量少用
}
}
class TicketTread extends Thread {
private int tick = 20;
public TicketTread(String name) {
super(name);
}
@Override
public void run() {
while (tick > 0) {
System.out.println(Thread.currentThread().getName()
+ "...sale....: " + tick--);
}
}
}
public class TicketRunDemo {
public static void main(String[] args) {
TicketRun t = new TicketRun();
Thread t1 = new Thread(t, "售票员1");
Thread t2 = new Thread(t, "售票员2");
Thread t3 = new Thread(t, "售票员3");
Thread t4 = new Thread(t, "售票员4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class TicketRun implements Runnable {
// 不需要static修饰
private int tick = 20;
@Override
public void run() {
while (tick > 0) {
System.out.println(Thread.currentThread().getName()
+ "...sale....: " + tick--);
}
}
}
线程状态
一、 线程状态类型
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()方法,该线程结束生命周期。
二、线程状态图如下: