java ——线程与并行

文章目录

    • 线程与并行
      • 1)定义在Runnable接口的run() 方法中。
      • 2)继承Thread类,重新定义run() 方法

线程与并行

额外加装CPU执行流程的进入点,有两种方法:

1)定义在Runnable接口的run() 方法中。

class Tortoise implements Runnable{
	....
	@Override
	public run()
	{
		...
	}
}
class Hare implements Runnable{
	....
	@Override
	public run()
	{
		...
	}
}

在主流程中启动线程执行额外流程:

      public class newtest{

    	public static void main(String[] args) {
	        //并发计算
	    	Tortoise tortoise=new Tortoise(10);
	    	Hare hare =new Hare(10);
	    	
	    	Thread tortoiseThread=new Thread(tortoise);
	    	Thread hareThread=new Thread(hare);
	    	
	    	tortoiseThread.start();
	    	hareThread.start();
    }

}

2)继承Thread类,重新定义run() 方法

class TortoiseThread extends Thread{
	....
	@Override
	public run()
	{
		...
	}
}

class HareThread extends Thread{
	....
	@Override
	public run()
	{
		...
	}
}

这两个类分别继承Thread重新定义run()方法,可以在main()主流程中,这样撰写程序来启动执行额外流程:

new TortoiseThread(10).start();
new HareThread(10).start();


事例代码:
1)定义在Runnable接口的run() 方法中。

//package chapter01;

/**
 * 并发和单线程执行测试
龟兔赛跑
 */


class Tortoise implements Runnable{
	    private int totalStep;
	   	private int step;
	   	Tortoise(int totalStep){
	   		this.totalStep=totalStep;
	   	}
	   	@Override
		
	   	public void run() {
	   		while(step<totalStep)
	   		{
	   			step++;
	   			System.out.printf("乌龟跑了%d步....%n", step);
	   		}
	   	}
   }
class Hare implements Runnable
{
	private boolean[] flags= {true,false};
	private int totalStep;
	private int step;
	
	Hare(int totalStep)
	{
		this.totalStep=totalStep;
	}
	@Override
	public void run() 
	{
		while(step<totalStep)
		{
			boolean isHaresleep=flags[((int)(Math.random()*10))%2];
			if(isHaresleep)
			{
				System.out.println("兔子睡着了zzzz");
			}
			else {
				step+=2;
				System.out.printf("兔子跑了%d步....%n", step);
			}
		}
		
	}
}
public class newtest{

    public static void main(String[] args) {
        //并发计算
    	Tortoise tortoise=new Tortoise(10);
    	Hare hare =new Hare(10);
    	
    	Thread tortoiseThread=new Thread(tortoise);
    	Thread hareThread=new Thread(hare);
    	
    	tortoiseThread.start();
    	hareThread.start();
    }

}

你可能感兴趣的:(Java)