版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34341457/article/details/77094985
java 多线程(一)简单实现
一、java创建线程的几种方式
(1)继承Thread类
Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()实例方法。
如:
public class tt extends Thread{
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("----"+i);
}
}
public static void main(String[] args) {
tt t = new tt();
tt t1 = new tt();
t.start();
t1.start();
}
}
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("----"+i);
}
}
public static void main(String[] args) {
tt t = new tt();
tt t1 = new tt();
t.start();
t1.start();
}
}
(2)实现Runable接口
public class tt implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("MyRunable"+"---"+i);
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new tt());
t1.start();
}
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("MyRunable"+"---"+i);
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new tt());
t1.start();
}
}
一般实现:
Runnable r1 = new Runnable()
{
@Override
public void run()
{
//代码块
}
};
Thread t1 = new Thread(r1);
t1.start();
{
@Override
public void run()
{
//代码块
}
};
Thread t1 = new Thread(r1);
t1.start();