建立线程
程序员文章站
2022-07-12 20:30:18
...
建立线程:
继承Thread类,重写run()方法;
实现Runnable接口,实现run()方法;
继承Thread类,重写run()方法;
实现Runnable接口,实现run()方法;
public class TestThread extends Thread{ public void run(){ boolean flag= true; System.out.println(getName()+"开始了"); int count = 0; while(flag){ System.out.println(getName()+"执行了"+(++count)); if(count %10 == 0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println(getName()+"结束了"); } public static void main(String[] args){ Thread threadB = new TestThread(); Thread threadA = new Thread(new TestThread(),"军队"); Thread threadC = new Thread(new TestThread2(),"将军"); threadB.setName("农民起义"); threadA.start(); threadB.start(); threadC.start(); } } class TestThread2 implements Runnable{ @Override public void run() { boolean flag= true; System.out.println(Thread.currentThread().getName()+"开始了"); int count = 0; while(flag){ System.out.println(Thread.currentThread().getName()+"执行了"+(++count)); if(count %10 == 0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println(Thread.currentThread().getName()+"结束了"); } }
上一篇: 排查CPU故障的方法和技巧
下一篇: 外贸加价算法