1.多线程的实现方式
1.继承Thread
public class Demo2_Thread {
/**
* @param args
*/
public static void main(String[] args) {
MyThread mt = new MyThread(); //4,创建自定义类的对象
mt.start(); //5,开启线程
for(int i = 0; i < 3000; i++) {
System.out.println("bb");
}
}
}
class MyThread extends Thread { //1,定义类继承Thread
public void run() { //2,重写run方法
for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
}
}
}
2.实现Runnable接口
public class Demo3_Runnable {
/**
* @param args
*/
public static void main(String[] args) {
MyRunnable mr = new MyRunnable(); //4,创建自定义类对象
//Runnable target = new MyRunnable();
Thread t = new Thread(mr); //5,将其当作参数传递给Thread的构造函数
t.start(); //6,开启线程
for(int i = 0; i < 3000; i++) {
System.out.println("bb");
}
}
}
class MyRunnable implements Runnable { //1,自定义类实现Runnable接口
@Override
public void run() { //2,重写run方法
for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
}
}
}
2.线程相关的API
1.setName:设置线程的名字
2.getName:获取线程的名字
3.Thread.currentThread().setName():设置当前线程的名字
4.Thread.currentThread().getName():获取当前线程的名字
5.Thread.Sleep():休眠线程(控制当前线程休眠)
6.Thread.SetDaemon(true):设置守护线程(设置一个线程为守护线程, 该线程不会单独执行, 当其他非守护线程都执行结束后, 自动退出)
7.Thread.join():加入进程(当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续)
8.Thread.setPriority() 设置线程的优先级(0到10 默认为5)
3.同步代码块
1.使用synchronized关键字加上一个锁对象来定义一段代码, 这就叫同步代码块
private static void print01() {
synchronized (Demo01_Synchronized.class) {
System.out.print("四");
System.out.print("海");
System.out.print("升");
System.out.print("平");
System.out.print("\r\n");
}
};
private static void print02() {
synchronized (Demo01_Synchronized.class) {
System.out.print("一");
System.out.print("二");
System.out.print("三");
System.out.print("四");
System.out.print("\r\n");
}
}
2.使用synchronized关键字修饰一个方法, 该方法中所有的代码都是同步的
1.非静态同步函数的锁是:this
2. 静态的同步函数的锁是:字节码对象
public static synchronized void print02() {
System.out.print("四");
System.out.print("海");
System.out.print("升");
System.out.print("平");
System.out.print("\r\n");
}