package RunnableTest;
/**
* 写多线程程序的四部曲
*
* 1、将需要用多线程方式执行的逻辑,写入一个runnable实现类中(run方法中);
* 2、创建出这个runnable实现类的对象;
* 3、利用这个runnable对象构造出n个thread线程;
* 4、将这n个thread启动(thread.start());
*
*
*/
public class Demo implements Runnable{
int id;
Demo(int input){
id=input;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("我的线程编号为:"+id);
}
public static void main(String[] args) throws Exception {
Demo runnable1 = new Demo(1);
Demo runnable2 = new Demo(2);
Demo runnable3 = new Demo(3);
Demo runnable4 = new Demo(4);
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable2);
Thread t3 = new Thread(runnable3);
Thread t4 = new Thread(runnable4);
t1.run();
t2.run();
t3.run();
t4.run();
System.out.println("---------------");
// 将这5个线程以多线程的方式同时运行
t1.start();
t2.start();
t3.start();
t4.start();
}
}
结果为:
我的线程编号为:1
我的线程编号为:2
我的线程编号为:3
我的线程编号为:4
---------------
我的线程编号为:1
我的线程编号为:4
我的线程编号为:3
我的线程编号为:2