标签:for over 上传 main highlight src val nbsp 多线程
先讲一下进程和线程
1.进程:操作系统中基本运行单元,qq运行时一个进程,酷狗音乐也是一个进程
2.线程:进程中独立运行的子任务,例如qq,可以一边聊天一边上传文件一边视频等
创建线程的两种方式:
1.继承Thread类,重写run方法
public class MyThread extends Thread{
@Override
public void run() {
for(int i=0;i<Integer.MAX_VALUE;i++){
try {
System.out.println(i);
Thread.sleep(1l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread thread0 = new MyThread();
MyThread thread1 = new MyThread();
thread0.start();
thread1.start();
}
}

结果是两个线程交替运行,互不干扰。
2.实现Runnable接口
public class MyThread implements Runnable {
@Override
public void run() {
for(int i=0;i<Integer.MAX_VALUE;i++){
System.out.println(i);
}
}
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread x = new Thread(mt);
Thread y = new Thread(mt);
x.start();
y.start();
}
}
两种多线程的实现方式

Thread类本身就是实现了Runnable接口
ok,采取第二种方式实现多线程更好,接口可以多实现,继承只能继承
标签:for over 上传 main highlight src val nbsp 多线程
原文地址:http://www.cnblogs.com/sunshine798798/p/7717828.html