黑马程序员技术交流社区
标题:
多线程
[打印本页]
作者:
a13783559191
时间:
2015-6-19 12:09
标题:
多线程
方式一:
实现步骤:
1、自定义线程类即生产线(继承Thread类)
2、重写Thread类中的run()方法,把希望能同时运行的代码放在run()方法中。
3、创建生产线,即创建线程类的对象并调用start()方法启动生产线
示例:
class Demo extends Thread { //生产线 (线程类)
public void run(){
for(int x=30; x<50; x++){
System.out.println("Thread----"+x);
}
}
}
class ThreadDemo {
public static void main(String[] args) { //主线程(必须有的)
Demo d1 = new Demo(); //创建一个生产线(线程)
d1.start(); //启动线程
for(int x=0; x<30; x++){
System.out.println("main----"+x);
}
}
}
方式二:
实现步骤:
1、创建假线程类即假生产线,覆盖Runnable接口中的run方法,把希望能同时运行的代码放在run()方法中。
2、创建生产线,即通过Thread类创建一个线程(构造方法需要一个线程类对象)。
3、启动生产线,即调用Thread类对象的start方法开启线程。
示例:
class Shengchanxian implements Runnable { //创建线程类(不是真正的生产线)
public void run(){
for(int j=0; j<30; j++){
System.out.println(Thread.currentThread().getName()+"-"+j);
}
}
}
class Demo{
public static void main(String[] args) { //主线程
Shengchanxian scx=new Shengchanxian();
Thread t1=new Thread(scx); //创建第一个生产线
t1.start(); //启动
Thread t2=new Thread(scx); //创建第二个生产线
t2.start(); //启动
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2