JAVA multi-threaded base of the Runnable interface

1. To achieve Runnable interface, rewriting run class
2. Start threads: + Thread incoming target object objects .start
because JAVA supports only single inheritance compared to more recommended Runnable interface Thread

Rush tickets simulation Multithreading

package 多线程基础Runable;

public class wed12306 implements Runnable {
	private int n=100;
	@Override
	public void run() {//重写run方法
		while (true) {
			System.out.println(Thread.currentThread().getName()+n);
			n--;
			if(n<=0) {
				break;
			}
		}
		
	}
	public static void main(String[] args) {
		new Thread(new wed12306(),"小王").start();//线程启动
		new Thread(new wed12306(),"小李").start();
		new Thread(new wed12306(),"小美").start();
	}
}

Here Insert Picture Description

Analog Tortoise and the Hare

package 多线程基础Runable;

public class race implements Runnable {

	private   static String winner;//当winnner为非空是线程结束
	@Override
	public void run() {
	for (int steps = 1; steps <= 100; steps++) {
		System.out.println(Thread.currentThread().getName()+steps);
		boolean flag =gameover(steps);
		if(flag==true) {
			break;
		}
	}
	}
	public boolean gameover(int steps) {
		if(winner!=null) {
			return true;//当有一个线程率先到达终点时,winner将会标记成true ,所以其他线程在此处不为空,也就结束了。
		}else if(steps==100) {
			winner=Thread.currentThread().getName();
			System.out.println(winner+"率先到达终点");
			return true;
		}else
			
			return false;
	}
	
	public static void main(String[] args) {
		new Thread(new race(),"乌龟").start();
		new Thread(new race(),"兔子").start();
	}
}

Here Insert Picture Description

Published 27 original articles · won praise 5 · Views 642

Guess you like

Origin blog.csdn.net/qq_44620773/article/details/104160656