JAVA之线程
一、创建线程的两种方式:
1、写一个类继承Thread类,并重写run方法:
public class ThreadDemo { public static void main(String[] args) { Boo boo = new Boo(); boo.start(); } } class Boo extends Thread{ @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } }
2、写一个类实现一个Runnable接口,并重写run方法:
public class ThreadDemo { public static void main(String[] args) { Coo coo = new Coo(); Thread tCoo = new Thread(coo); tCoo.start(); //接口启动需要先创建Thread对象,将接口对象传入Thread()后,再使用Thread对象启动 new Thread(new Coo()).start(); //一行写Thread对象并启动的方式 } class Coo implements Runnable{ @Override public void run() { for (int i = 10; i < 20; i++) { System.out.println(i); } } }
二、启动线程的方式:
1、启动继承Thread类的类的对象:
public class ThreadDemo { public static void main(String[] args) { Boo boo = new Boo(); // boo.run();//不要调用.run(),调用的是方法,跟线程一点关系都没有 boo.start(); //用.start()这个方法,线程启动什么它就执行什么,它会自己执行run方法 } } class Boo extends Thread{ @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } }
2、启动实现Runnable接口的类的对象:
public class ThreadDemo { public static void main(String[] args) { Coo coo = new Coo(); Thread tCoo = new Thread(coo); tCoo.start(); //方式1
new Thread(new Coo()).start(); //方式2 } } class Coo implements Runnable{ @Override public void run() { for (int i = 10; i < 20; i++) { System.out.println(i); } } }
三、线程个数:
public class ThreadDemo { public static void main(String[] args) { //线程1 Boo boo = new Boo(); boo.start(); //线程2 Coo coo = new Coo(); Thread tCoo = new Thread(coo); tCoo.start(); //线程3 new Thread(new Coo()).start(); //线程4 System.out.println("AAAA"); //线程的执行是无序的,是由CPU决定的,使用哪个CPU,就执行哪个线程 } //main()方法本身是一个线程,所以上面一共有4个线程: // (1)boo.start() (2)tCoo.start() (3)new Thread(new Coo()).start() (4)main() } class Boo extends Thread{ @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } } class Coo implements Runnable{ @Override public void run() { for (int i = 10; i < 20; i++) { System.out.println(i); } } }
每天进步一点点,快乐生活多一点。