并发 如何创建线程 多线程
进程:一个程序的执行过程
线程:一个方法就是一个线程
并发:多个线程抢夺一个资源 操作同一个对象
创建线程方法1
//创建线程方法1 继承Thread类 重写润方法 调用start开启线程
public class TestThead extends Thread{@Overridepublic void run() {super.run();//模拟延迟Thread.sleep(1000);}//main线程 主线程public static void main(String[] args) {//创建一个线程对象TestThead t1=new TestThead();//调用start方法开启线程t1.start();}
}
创建线程方法2
//创建线程方2 继承Runnable接口实现run方法
public class TestThead implements Runnable{@Overridepublic void run() {for(int i=1;i<1000;i++){System.out.println("我是小猫");}}//main线程 主线程public static void main(String[] args) {//创建一个Runnable接口的实现类对象TestThead t1=new TestThead();// 创建线程对象 通过现成对象来开启线程Thread thead=new Thread(t1);thead.start();for(int i=1;i<1000;i++){System.out.println("喵喵");}}
}