一、实现多线程的两种方式
1.继承Tread类
2.实现Runnable接口
3.匿名内部类
二、具体实现
1.继承Tread类
1 public class Demo2_Thread { 2 public static void main(String[] args) { 3 MyThread mt = new MyThread(); //4,创建自定义类的对象 4 mt.start(); //5,开启线程 5 for(int i = 0; i < 1000; i++) { 6 System.out.println("bb"); 7 } 8 } 9 10 } 11 12 13 class MyThread extends Thread { //1,定义类继承Thread 14 public void run() { //2,重写run方法 15 for(int i = 0; i < 1000; i++) { //3,将要执行的代码,写在run方法中 16 System.out.println("aaaaaaaaaa"); 17 } 18 } 19 }
2.实现Runnable接口
1 public class Demo3_Runnable { 2 /** 3 * @param args 4 */ 5 public static void main(String[] args) { 6 MyRunnable mr = new MyRunnable(); //4,创建自定义类对象 7 //Runnable target = new MyRunnable(); 8 Thread t = new Thread(mr); //5,将其当作参数传递给Thread的构造函数 9 t.start(); //6,开启线程 10 11 for(int i = 0; i < 3000; i++) { 12 System.out.println("bb"); 13 } 14 } 15 } 16 17 class MyRunnable implements Runnable { //1,自定义类实现Runnable接口 18 @Override 19 public void run() { //2,重写run方法 20 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 21 System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); 22 } 23 } 24 25 }
3.匿名内部类实现两种方式
new Thread() { //1,new 类(){}继承这个类 public void run() { //2,重写run方法 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } } }.start();
new Thread(new Runnable(){ //1,new 接口(){}实现这个接口 public void run() { //2,重写run方法 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 System.out.println("bb"); } } }).start();
三、多线程同步代码块问题’
1.什么情况下需要同步 * 当多线程并发, 有多段代码同时执行时, 我们希望某一段代码执行的过程中CPU不要切换到其他线程工作. 这时就需要同步. * 如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码. * 2.同步代码块 * 使用synchronized关键字加上一个锁对象来定义一段代码, 这就叫同步代码块 * 多个同步代码块如果使用相同的锁对象, 那么他们就是同步的
像这样嵌套锁的话会出现死锁现象注意不要嵌套使用
public class Test002 { private static String s1 = "筷子左"; private static String s2 = "筷子右"; public static void main(String[] args) { new Thread() { public void run() { while(true) { synchronized(s1) { System.out.println(getName()+"获取"+s1+"等待"+s2); synchronized(s2) { System.out.println(getName()+"拿到"+s2+"开吃"); } } } } }.start(); new Thread() { public void run() { while(true) { synchronized(s2) { System.out.println(getName()+"获取"+s2+"等待"+s1); synchronized(s1) { System.out.println(getName()+"拿到"+s1+"开吃"); } } } } }.start(); } }