由于cpu运行速度很快,能在极短的时间内在不同的进程(线程)中进行切换,所以给人以同时执行多个程序(线程)的错觉。
继承thread类创建多线程:
public class Example01{
public void static main(String[] args){
MyThread myThread = new MyThread();
myThread.run();
System.out.println("main方法正在运行");
}
}
class MyThread {
public void run(){
System.out.println("MyThread类的run方法正在运行");
}
}
这个程序的执行情况与下面的程序不一样:
public class Example02{
public void static main(String[] args){
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread,"第一个runnable线程");
myThread.start();
/*
new Thread(myThread , "第一个runnable线程").start();
*/
while(true){
System.out.println("main方法正在运行");
}
}
}
calss MyThread implements Runable{
public void run(){
while(true){
System.out.println("MyThread类的run方法正在运行");
}
}
}
直接继承thread和实现runnable接口的区别:
public class Example03{
public void static main(String[] args){
new TicketWindow().start();
new TicketWindow().start();
new TicketWindow().start();
new TicketWindow().start();
}
}
class TicketWindow extends Thread {
private int tickets = 100;
public void run(){
while(true){
if(tickets > 0){
Thread th = Thread.currentThread();
String th_name = th.getName();
System.out.println(th_name+"正在发售第"+tickets-- + "张票");
}
}
}
}
上边这种方法,会卖400张票出去
public class Example04 {
public void static main(String[] args){
TicketWindow ticketWindow = new TicketWindow();
new Thread(tw,"窗口1");
new Thread(tw,"窗口2");
new Thread(tw,"窗口3");
new Thread(tw,"窗口4");
}
}
class TicketWindow implements Runnable {
private int tickets = 100;
public void run(){
while(true){
if(tickets > 0 ){
Thread th = Thread.currentThread();
String th_name = th.getName();
System.out.println(th_name+"正在发售第"+tickets-- +"张票");
}
}
}
}
实现runnable就可以卖100张而不是400张出去
那么,实现Runnable的线程比直接继承Thread的线程的好处:
1)适合多个相同代码的线程去处理同一个资源的情况
2)可以避免java语言的单继承带来的局限性
|
|