一, 线程的创建
方式一: 继承 Thread 类, 重写 run() 方法
- package com.imooc.thread1;
- class MyThread extends Thread{
- public MyThread(String name) {
- super(name);
- }
- public void run() {
- for(int i=1;i<=10;i++) {
- System.out.println(getName()+"正在运行~~"+i);
- }
- }
- }
- public class ThreadTest1 {
- public static void main(String[] args) {
- MyThread mt1=new MyThread("线程 1");
- MyThread mt2=new MyThread("线程 2");
- mt1.start();
- mt2.start();
- }
- }
2, 通过实现 Runnable 接口创建线程
- package com.imooc.thread3;
- class PrintRunnable implements Runnable{
- @Override
- public void run() {
- // 重写接口的 run() 方法
- int i=1;
- while(i<=10) {
- System.out.println(Thread.currentThread().getName()+"正在运行!"+(i++));
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- // 通过实现 Runnable 接口创建线程
- //1. 实例化 Runnable 接口的实现类
- PrintRunnable pr=new PrintRunnable();
- //2. 创建线程对象
- Thread t1=new Thread(pr);
- //3. 启动线程
- t1.start();
- PrintRunnable pr2=new PrintRunnable();
- //2. 创建线程对象
- Thread t2=new Thread(pr2);
- //3. 启动线程
- t2.start();
- }
- }
3, 多个线程共享资源
- package com.imooc.thread3;
- class PrintRunnable implements Runnable{
- int i=1;
- @Override
- public void run() {
- // 重写接口的 run() 方法
- while(i<=10) {
- System.out.println(Thread.currentThread().getName()+"正在运行!"+(i++));
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- // 通过实现 Runnable 接口创建线程
- //1. 实例化 Runnable 接口的实现类
- PrintRunnable pr=new PrintRunnable();
- //2. 创建线程对象, 参数为同一个对象, 多个线程共享对象资源
- Thread t1=new Thread(pr);
- Thread t2=new Thread(pr);
- //3. 启动线程
- t1.start();
- t2.start();
- }
- }
来源: http://www.bubuko.com/infodetail-3117189.html