线程

1.创建线程的三种方式:

1.1继承Thread

  • 定义类继承Thread
  • 重写run方法
  • 把新线程要做的事写在run方法中
  • 创建线程对象
  • 开启新线程, 内部会自动执行run方法
	public class ChThread01 {
		public static void main(String[] args) {
			// 4.创建Thread类的子类对象
			Thread myThread = new MyThread();
			// 5.开启线程,调用run方法
			myThread.start();
			for (int i = 0; i < 5; i++) {
				System.out.println("BBBBBBBBBBB");
			}
		}
	}
	
	//1.继承Thread方法
	class MyThread extends Thread {
		// 2.重写run方法
		public void run() {
			// 3.在run方法内写入要执行的代码
			for (int i = 0; i < 5; i++) {
				System.out.println(i + "AAAAAAAAAAA");
			}
		}
	}

1.2实现Runnable接口

  • 定义类实现Runnable接口
  • 实现run方法
  • 把新线程要做的事写在run方法中
  • 创建自定义的Runnable的子类对象
  • 创建Thread对象, 传入Runnable
  • 调用start()开启新线程, 内部会自动调用Runnable的run()方法
	public class ChThread02 {
		public static void main(String[] args) {
			MyRunnable mr = new MyRunnable();	//4,创建Runnable的子类对象
			Thread t = new Thread(mr);			//5,将其当作参数传递给Thread的构造函数
			t.start();							//6,开启线程
			for (int i = 0; i < 50; i++) {
				System.out.println("BBBBBBBBBBB");
			}
		}
	}
	//1.创建类实现Runable
	class MyRunnable implements Runnable{
		//2.重写run方法
		@Override
		public void run() {
			for (int i = 0; i < 50; i++) { 		// 3.在run方法内写入要执行的代码
				System.out.println(i + "AAAAAAAAAAA");
			}
		}
	}

1.3匿名内部类

public class ChThread03 {
	public static void main(String[] args) {
		//继承Thread类
		new Thread() {										//1,继承Thread类
			public void run() {								//2,重写run方法
				for(int i = 0; i < 50; i++) {				//3,将要执行的代码写在run方法中
					System.out.println("aaaaaaaaaaaaaa");
				}
			}
		}.start();											//4,开启线程
		//实现Runnable接口
		new Thread(new Runnable() {							//1,将Runnable的子类对象传递给Thread的构造方法
			public void run() {								//2,重写run方法
				for(int i = 0; i < 50; i++) {				//3,将要执行的代码写在run方法中
					System.out.println("bb");
				}
			}
		}).start();											//4,开启线程
	}
}

a. 继承Thread : 由于子类重写了Thread类的run(), 当调用start()时, 直接找子类的run()方法
b. 实现Runnable : 构造函数中传入了Runnable的引用, 成员变量记住了它, start()调用run()方法时内部判断成员变 量Runnable的引用是否为空, 不为空编译时看的是Runnable的run(),运行时执行的是子类的run()方法

  • 继承Thread
    好处是:可以直接使用Thread类中的方法,代码简单
    弊端是:如果已经有了父类,就不能用这种方法
  • 实现Runnable接口
    好处是:即使自己定义的线程类有了父类也没关系,因为有了父类也可以实现接口,而且接口是可以多实现的
    弊端是:不能直接使用Thread中的方法需要先获取到线程对象后,才能得到Thread的方法,代码复杂

2.线程的部分方法

2.1setName() getName()

  • 通过setName()方法为线程写入名字
  • 通过getName()方法获取线程名字
	//1.通过构造方法直接给name赋值
	new Thread("芙蓉姐姐") {
		public void run() {
			System.out.println(this.getName() + "....aaaaaaaaa");
		}
	}.start();
	//2.创建线程后通过setName()方法给线程命名
	Thread t1 = new Thread() {
		public void run() {
			System.out.println(this.getName() + "....aaaaaaaaaaaaa");
		}
	};
	t1.setName("张三");
	//3.直接在run方法内部给线程命名
	new Thread() {
		public void run() {
			this.setName("张三");
			System.out.println(this.getName() + "....aaaaaaaaaaaaa");
		}
	}.start();

2.2Thread.currentThread()获取当前正在执行的线程的引用

获取主线程

public class ChThread03 {
	public static void main(String[] args) {
		//继承Thread类
		new Thread() {										//1,继承Thread类
			public void run() {								//2,重写run方法
				for(int i = 0; i < 50; i++) {				//3,将要执行的代码写在run方法中
					System.out.println("aaaaaaaaaaaaaa");
				}
			}
		}.start();											//4,开启线程
		//实现Runnable接口
		new Thread(new Runnable() {							//1,将Runnable的子类对象传递给Thread的构造方法
			public void run() {								//2,重写run方法
				for(int i = 0; i < 50; i++) {				//3,将要执行的代码写在run方法中
					System.out.println(Thread.currentThread().getName()+"bb");
				}
			}
		}).start();											//4,开启线程
		//获取主线程并输出主线程名
		System.out.println(Thread.currentThread().getName());
	}
}

2.3sleep休眠线程方法

  • Thread.sleep(毫秒,纳秒), 控制当前线程休眠若干毫秒1秒= 1000毫秒
	public class ChThread06 {
		public static void main(String[] args) {
			new Thread() {
				public void run() {
					for (int i = 0; i < 5; i++) {
						try {
							// Sleep休眠,到时间后自动会醒来
							// Wait方法,等待,没人叫不会醒
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(getName() + i + "aaa");
					}
				}
			}.start();
		}
	}

2.4setDaemon()守护线程

  • setDaemon(), 设置一个线程为守护线程, 该线程不会单独执行, 当其他非守护线程都执行结束后, 自动退出
public class ChThread07 {
	public static void main(String[] args) {
		Thread t1 = new Thread() {
			public void run() {
				for(int i=0;i<3;i++) {
					System.out.println(getName()+"AAA");
				}
			}
		};
		
		Thread t2 = new Thread() {
			public void run() {
				for(int i=0;i<30;i++) {
					System.out.println(getName()+i+"BBB");
				}
			}
		};
		
		t2.setDaemon(true);//设置为守护线程
		t1.setName("主线程");
		t2.setName("守护线程");
		t1.start();
		t2.start();
	}
}

2.5join()加入线程

  • join(), 当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续
  • join(long), 可以等待指定的毫秒之后继续
public class ChThread08 {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread() {
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(getName()+i+"AAA");
				}
			}
		};
		
		Thread t2 = new Thread() {
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					if (i==3) {
						try {
							t1.join();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(getName()+i+"BBB");
				}
			}
		};
		
		t1.setName("A线程");
		t2.setName("B线程");
		
		t1.start();
		t2.start();
		
	}
}

2.6 synchronized

synchronized同步代码块
  • 1.什么情况下需要同步
    当多线程并发, 有多段代码同时执行时,我们希望某一段代码执行的过程中CPU不要切换到其他线程工作. 这时就需要同步。
    如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码。
  • 2.同步代码块
    使用 synchronized 关键字加上一个锁对象来定义一段代码, 这就叫同步代码块。
    多个同步代码块如果使用相同的锁对象, 那么他们就是同步的。
/**
	 * @param args
	 * 同步代码块
	 */
	public static void main(String[] args) {
		final Printer p = new Printer();
		
		new Thread() {
			public void run() {
				while(true) {
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					p.print1();
				}
			}
		}.start();
		
		new Thread() {
			public void run() {
				while(true) {
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					p.print2();
				}
			}
		}.start();
	}
 
}
 
class Printer {
//	Demo d = new Demo();
	public void print1() {
		//synchronized(new Demo()) {							//同步代码块,锁机制,锁对象可以是任意的
		synchronized(Printer.class) {
			//System.out.println("博雅程序员");
			System.out.print("博");
			System.out.print("雅");
			System.out.print("程");
			System.out.print("序");
			System.out.print("员");
			System.out.print("\r\n");
		}
	}
	
	public void print2() {
		//synchronized(new Demo()) {							//锁对象不能用匿名对象,因为匿名对象不是同一个对象
		synchronized(Printer.class) {	
			//System.out.println("博雅");
			System.out.print("j");
			System.out.print("a");
			System.out.print("v");
			System.out.print("a");
			System.out.print("\r\n");
		}
	}
}
//定义的锁类
class Demo{}

使用synchronized将线程中要执行的代码块包裹起来,那么直到该代码块执行完成一次,否则别的线程不能抢占cpu

synchronized同步方法

与同步代码块类似,使用synchronize修饰方法。
非静态同步方法:

	//非静态的同步方法的锁对象是this
	public synchronized void print1() {					//同步方法只需要在方法上加synchronized关键字即可
		System.out.print("博");
		System.out.print("雅");
		System.out.print("程");
		System.out.print("序");
		System.out.print("员");
		System.out.print("\r\n");
	}
	
	public void print2(this) {
		synchronized(Printer2.class) {		
			System.out.print("j");
			System.out.print("a");
			System.out.print("v");
			System.out.print("a");
			System.out.print("\r\n");
		}
	}

静态同步方法:

    //静态的同步方法的锁对象是该类的字节码对象
	public static synchronized void print1() {				//同步方法只需要在方法上加synchronized关键字即可
		System.out.print("博");
		System.out.print("雅");
		System.out.print("程");
		System.out.print("序");
		System.out.print("员");
		System.out.print("\r\n");
	}
	
	public static void print2() {
		synchronized(Printer2.class) {		
			System.out.print("j");
			System.out.print("a");
			System.out.print("v");
			System.out.print("a");
			System.out.print("\r\n");
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值