什么是线程
线程是程序在执行过程中,能够执行程序代码的一个执行单元。
多线程
使用多线程有两种常用方法
继承Thread类,重写run()方法。
实现Runnable接口,并实现该接口的run)方法。
public class Test {
public static void main(String[] args) {
int count = 0;
new Thread(new MyThread()).start();
new Thread(new MyThread1()).start();
new Thread(new MyThread1()).start();
while (true) {
System.out.println(Thread.currentThread().getName()+"--"+count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
int count = 0;
while (true) {
System.out.println(Thread.currentThread().getName()+"--"+count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class MyThread1 implements Runnable{
@Override
public void run() {
int count = 0;
while (true) {
System.out.println(Thread.currentThread().getName()+"--"+count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
int count = 0;
while (true) {
System.out.println(Thread.currentThread().getName()+"--"+count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}