package ch;
public class thread_1 {
	public static void main(String [] args) {
		DemoThread dt = new DemoThread();
		dt.start();
		for(int i = 0;i<20;i++) {
			System.out.println("main i======"+i);
		}
			}
}
class DemoThread extends Thread{
	@Override
	public void run() {
		for(int i = 0; i<20;i++) {
			System.out.println("DemoThread run i=" +i);
			}
		}
	}
package ch;

public class Thread_2 {
	public static void main(String[] args) {
		// 创建实现类对象,明确线程要执行的任务对象
		Ticket tk = new Ticket();

		// 创建线程对象
		Thread t1 = new Thread(tk);
		Thread t2 = new Thread(tk);
		Thread t3 = new Thread(tk);
		Thread t4 = new Thread(tk);

		// 开启线程
		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}
}

class Ticket implements Runnable {
	private int sum = 100;
	//定义同步中的锁对象
	private Object lock = new Object();

	@Override
	public void run() {

		while (true) {
			synchronized (lock) {
				if (sum > 0) {
					System.out.println(Thread.currentThread().getName() + "正在售出的票是" + sum);
					sum--;
				}
			}
		}
	}
}

开启线程的两种方式

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2021-09-30
  • 2021-08-12
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-04
  • 2021-09-04
  • 2022-12-23
  • 2021-07-08
  • 2022-01-14
相关资源
相似解决方案