java线程案例

继承Thread类,重写run方法,实现线程

public class Practice {
	public static void main(String[] args) throws IOException {
		NewThread t1=new NewThread();
		t1.start();
	}	
}
class NewThread extends Thread{
	private int i=0;
	@Override
	public  void run() {
		while(i<100){
			System.out.println(Thread.currentThread().getName()+":"+i+"是猪吗");
			i++;
			}
	}
}

实现Runnable接口,重写run方法,实现线程

public class Practice {
	public static void main(String[] args) throws IOException {
		NewThread f=new NewThread();
		Thread t1=new Thread(f,"电影院");
		t1.start();	
	}	
}
class NewThread implements Runnable{
	private int i=0;
	@Override
	public  void run() {
		while(i<100){
			System.out.println(Thread.currentThread().getName()+":"+i+"是猪吗");
			i++;
			}
	}
}

使用ReentrantLock类实现线程同步,售卖电影票初始逻辑

import java.util.concurrent.locks.ReentrantLock;
public class Practice {
	public static void main(String[] args) throws IOException {
		ReentrantLock lock=new ReentrantLock();
		NewThread f=new NewThread(lock);
		FileThread f1=new FileThread(lock);
		Thread t1=new Thread(f,"电影院");
		Thread t2=new Thread(f1,"猫眼app");
		System.out.println(t1.getId());
		t1.start();
		t2.start();
		
	}	
}
class NewThread implements Runnable{
	private ReentrantLock lock=null;
	public NewThread(ReentrantLock lock) {
		this.lock=lock;
	}
	@Override
	public  void run() {
		while(Number.i<100){
			lock.lock();
			System.out.println(Thread.currentThread().getName()+":"+Number.i+"是猪吗");
			Number.i++;
			lock.unlock();
			}
	}
}
class FileThread implements Runnable{
	ReentrantLock lock=null; 
	public FileThread(ReentrantLock lock) {
		this.lock=lock;
	}
	@Override
	public void run() {
		while(Number.i<100){
				lock.lock();
				System.out.println(Thread.currentThread().getName()+":"+Number.i+"是猪吗");
				Number.i++;
				lock.unlock();
				}
	}
	
}
class Number{
	public static int i=0;
}

使用sychronized(Object objectname)实现线程同步

public class Practice {
	public static void main(String[] args)  {
		Object lock=new Object();
		NewThread f=new NewThread(lock);
		FileThread f1=new FileThread(lock);
		Thread t1=new Thread(f,"电影院");
		Thread t2=new Thread(f1,"猫眼app");
		t1.start();
		t2.start();	
	}	
}
class NewThread implements Runnable{
	private Object lock=null;
	public NewThread(Object lock) {
		this.lock=lock;
	}
	@Override
	public  void run() {
		while(Number.i<100){
			synchronized (lock) {
				System.out.println(Thread.currentThread().getName()+":"+Number.i+"是猪吗");
				Number.i++;
			}
			}
	}
}
class FileThread implements Runnable{
	private Object lock=null;
	public FileThread(Object lock) {
		this.lock=lock;
	}
	@Override
	public  void run() {
		while(Number.i<100){
			synchronized (lock) {
				System.out.println(Thread.currentThread().getName()+":"+Number.i+"是猪吗");
				Number.i++;
			}
			}
	}
}
class Number{
	public static int i=0;
}


发布了6 篇原创文章 · 获赞 1 · 访问量 143

猜你喜欢

转载自blog.csdn.net/qq_39655942/article/details/104542887
今日推荐