多线程

 一个进程对应多个线程
一个项目是一个进程 main方法是一个线程。

代码块分为以下四种

静态代码块

static{
}

同步代码块

构造代码块

{
}

普通代码块


方法类

class A extends Thread02{
	private String m;

	@Override
	public void run() {
		for(int i=0;i<100;i++) {
			System.out.print(m);
		}
	}

	public A() {
	System.out.println("this is no parameter method");
	}
	static {
		System.out.println("this is static piece");
	}
	{
		
		System.out.println("this is construct piece");
	}

	public A(String m) {
		System.out.println("this is parameter method");
		this.m = m;
	}

	public String getM() {
		return m;
	}

	public void setM(String m) {
		this.m = m;
	}
	
	
}

主方法

public class Thread02 extends java.lang.Thread {

	public static void main(String[] args) {
		A a=new A();
		A b=new A();
		//a.setM("mm");
		//b.setM("yyy");
		a.start();
		b.start();
		
	}
	
	
}

运行结果


静态——构造代码块——构造方法


 Thread 类是多个线程分别完成自己的任务,Runnable接口是多个线程共同完成一个任务。

Thread类:自己本身就是多线程类,其本身包含很多关于线程操作的方法,启动与调用都很简单;如果实现数据共享的话,需要创建父类对象并调用父类构造方法,启动与runnable一样复杂

Runnable : 启动需要依靠Thread类来完成,但是避免了我们java单继承的局限性

新建:程序每new一个线程对象,都是新建

就绪:当我们调用start()方法后

执行:当线程抢到资源后并开始执行代码

消亡:运行完毕,或者是系统崩溃;出现异常和错误

堵塞:当前线程抢占到资源

sleep 与wait的区别

两者是不同类的提供的方法

sleep 可以这是时间自动唤醒

wait 可以通过notifyall 与notify 进行人工唤醒;


使用接口实现多线程

class A implements Runnable{
	private String m;
public static void main(String[] args) {
	new Thread(new A("a")).start();
	new Thread(new A("b")).start();

	
	
}
	@Override
	public void run() {
		for(int i=0;i<100;i++) {
			System.out.print(m);
		}
	}

	public A() {
	System.out.println("this is no parameter method");
	}
	static {
		System.out.println("this is static piece");
	}
	{
		
		System.out.println("this is construct piece");
	}

	public A(String m) {
		System.out.println("this is parameter method");
		this.m = m;
	}

	public String getM() {
		return m;
	}

	public void setM(String m) {
		this.m = m;
	}
	
	
}


线程起名字

	Thread a=new Thread(new A("a"));
	Thread b=new Thread(new A("b"));
	a.setName("a");
	b.setName("b");

	a.start();
	b.start();

构造方法命名

	new Thread(z, "WW").start();



synchronized 同步,只允许一个线程进入;对thread.sleep 进行锁定同步,然其未进入同步过程的线程进行等待;

	@Override
	public  void run() {
		for(int  i=0;i<50;i++) {
			synchronized (this){	if(ticket>0) {
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
				System.out.print(Thread.currentThread().getName()+ticket--+" ");
				s++;
			}
			else {
				break;
			}
			}
		}
				System.out.println();
		System.out.println(Thread.currentThread().getName()+"共进行"+s+"次");

	}

上式运行结果可以得到三个窗口同步卖票

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值