多线程

//一种方法是将类声明为 Thread 的子类。该子类应重写 Thread 类的 run 方法。接下来可以分配并启动该子类的实例(不推荐)

//另一种方法是声明实现 Runnable 接口的类。该类然后实现 run 方法。然后可以分配该类的实例,在创建 Thread 时作为一个参数来传递并启动。(推荐)


//使用方法二创建一个测试类
public class MyThread2 implements Runnable {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i!=100;i++)
		{
			Thread t = Thread.currentThread();
			System.out.println(t.getName() + ":" + i);
		}
	}
}



//多线程
private static void method2() {
	MyThread2 m = new MyThread2();
	Thread t = new Thread(m);
	t.setName("Hei");
	t.start();
	
	Thread t2 = new Thread(m);
	t2.setName("Hello");
	t2.start();
}

多线程出现的问题

现象

//static void sleep(long millis):让当前线程停一会
public class Ticket implements Runnable{
	
	int ticket;
	public Ticket(int ticket)
	{
		this.ticket = ticket;
	}
	public void run() {
		// TODO Auto-generated method stub
		Thread t = Thread.currentThread();
		while(true)
		{
			if(ticket>0)
			{
				System.out.println(t.getName() + ":" + ticket);
				ticket--;
			}
			else
				break;
		}
	}
	
}


private static void method3() {
	Ticket tk = new Ticket(100);
	Thread t1 = new Thread(tk);
	Thread t2 = new Thread(tk);
	Thread t3 = new Thread(tk);
	
	t1.setName("售票口1");
	t2.setName("售票口2");
	t3.setName("售票口3");
	
	t1.start();
	t2.start();
	t3.start();
}

解决方法(增加mutex互斥锁)

public class Ticket implements Runnable{
	
	int ticket = 100;
	Object mutex = new Object();
	@Override
	public void run() {                // 注意
		// TODO Auto-generated method stub
		Thread t = Thread.currentThread();
		while(true)
		{
			synchronized(mutex)                //注意
			{
				if(ticket>0)
				{
					System.out.println(t.getName() + ":" + ticket);
					ticket--;
				}
				else
					break;
			}
		}
	}
}

//或者(锁的位置不同)
public class Ticket implements Runnable{
	
	int ticket = 100;
	Object mutex = new Object();
	@Override
	public synchronized void run() {       // 注意
		// TODO Auto-generated method stub
		Thread t = Thread.currentThread();
		while(true)
		{
			if(ticket>0)
			{
				System.out.println(t.getName() + ":" + ticket);
				ticket--;
			}
			else
				break;
		}
	}
}

版权声明:本文为pupil2021原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/selfdef/p/11077934.html