twothread.java

来自「介绍有关java的资料 课件 相当一本书籍 里面都是很基础的知识」· Java 代码 · 共 35 行

JAVA
35
字号
		public class TwoThread {
   			public static void main(String args[]) {
      			DelayPrintThread thread1,thread2;
				thread1 = new DelayPrintThread();		// 创建2个线程对象
				thread2 = new DelayPrintThread();
				thread1.start();						//开始执行2个线程
				thread2.start();
				try {
					Thread.sleep( 10000 );				//主线程休眠1万毫秒
				}
				catch(InterruptedException e) {
					System.out.println("thread has wrong");
				}
			}
		}
		class DelayPrintThread extends Thread {
			private static int threadCount = 0;
			private int threadNumber = 0;
			private int delay;
			public DelayPrintThread() {
				delay = (int)(Math.random()*5000);		//计算休眠时间
				threadCount++;							//线程计数
				threadNumber = threadCount;				//线程号
			}
			public void run() {
				try {
					sleep( delay );				//子线程休眠一段时间:delay
				}
				catch ( InterruptedException e ) {
				}
				System.out.println( "This is Thread# "+threadNumber+
									" with a delay of "+delay+"." );
			}
		}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?