Java基础之多线程

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");
			}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值