实现Runnable接口
public class TestThread03 implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
System. out. println ( "我在看代码----" + i) ;
}
}
public static void main ( String[ ] args) {
TestThread03 testThread03 = new TestThread03 ( ) ;
new Thread ( testThread03) . start ( ) ;
for ( int i = 0 ; i < 20 ; i++ ) {
System. out. println ( "我在学习多线程----" + i) ;
}
}
}
下载图片
public class TestThread02 implements Runnable {
private String url;
private String name;
public TestThread02 ( String url, String name) {
this . url = url;
this . name = name;
}
@Override
public void run ( ) {
WebDownLoad webDownLoad = new WebDownLoad ( ) ;
webDownLoad. downLoader ( url, name) ;
System. out. println ( "下载了名为" + name + "的图片" ) ;
}
public static void main ( String[ ] args) {
TestThread02 t1 = new TestThread02 ( "http://i0.hdslb" +
".com/bfs/space/768cc4fd97618cf589d23c2711a1d1a729f42235.png" ,
"E:\\学习\\Java\\代码相关\\多线程\\src\\com\\tr\\demo01\\bilibili,jpg" ) ;
TestThread02 t2 = new TestThread02 ( "http://i0.hdslb.com/bfs/album" +
"/c3c703eb8740ac7949e6d2c0213b5786a83220c3.jpg@518w.jpg" , "E:\\学习\\Java" +
"\\代码相关\\多线程\\src\\com\\tr\\demo01\\冰冰.jpg" ) ;
TestThread02 t3 = new TestThread02 ( "http://i0.hdslb" +
".com/bfs/space/cb1c3ef50e22b6096fde67febe863494caefebad.png" , "E" +
":\\学习\\Java\\代码相关\\多线程\\src\\com\\tr\\demo01\\space" +
".jpg" ) ;
new Thread ( t1) . start ( ) ;
new Thread ( t2) . start ( ) ;
new Thread ( t3) . start ( ) ;
}
}
class WebDownLoad {
public void downLoader ( String url, String name) {
try {
FileUtils. copyURLToFile ( new URL ( url) , new File ( name) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
小结
继承Thread类
子类继承Thread类具备多线程能力 启动线程:子类对象.start() 不建议使用:避免OOP单继承局限性
实现Runnable接口
实现接口Runnable具有多线程能力 启动线程:传入目标对象 + Thread对象.start() 推荐使用:避免的单继承局限性,灵活多变,方便同一个对象被多个线程使用