多线程

定义:同时对多项任务加以控制

继承Thread类

package 多线程;

public class Thread1 extends Thread {
	
	
	private int baoZi=1;
	
	private String threadName;

	public Thread1(String threadName) {
		super();
		this.threadName = threadName;
	}

	@Override
	public void run() {
		while(baoZi<10){
			System.out.println(threadName+"在吃第"+baoZi+"个包子");
			baoZi++;
		}
	}

	public static void main(String[] args) {
		Thread1 thread1=new Thread1("张三线程");
		Thread1 thread12=new Thread1("李四线程");
		thread1.start();
		thread12.start();
	}
}

实现Runnable接口

package 多线程;

public class Thread2 implements Runnable {
	private int baoZi=1;
	
	private String threadName;

	public Thread2(String threadName) {
		super();
		this.threadName = threadName;
	}

	@Override
	public void run() {
		while(baoZi<10){
			System.out.println(threadName+"在吃第"+baoZi+"个包子");
			baoZi++;
		}
	}

	public static void main(String[] args) {
		Thread2 thread1=new Thread2("张三线程");
		Thread2 thread12=new Thread2("李四线程");
		Thread t11=new Thread(thread1);
		Thread t12=new Thread(thread12);
		t11.start();
		t12.start();
	}
}

多线程实现数据共享

package 多线程;

public class Thread3 implements Runnable {
	private int baoZi=1;
	
	private String threadName;

	public Thread3(String threadName) {
		super();
		this.threadName = threadName;
	}
	
	//上锁synchronized,同一时间只允许一个进程进去执行方法
	@Override
	public synchronized void run() {
		while(baoZi<=10){
			System.out.println(threadName+"在吃第"+baoZi+"个包子");
			baoZi++;
		}
	}

	public static void main(String[] args) {
		Thread3 thread1=new Thread3("超级张三线程");
		Thread t11=new Thread(thread1);
		Thread t12=new Thread(thread1);
		Thread t13=new Thread(thread1);
		t11.start();
		t12.start();
		t13.start();
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值