多线程
作者:互联网
1.多线程的创建
2.线程启动
new 对象然后调用start()方法,如果先启动多个线程,就先创建多个对象。
3.常用方法
1 class HelloThread extends Thread{ 2 public void run(){ 3 for (int i = 0; i < 100; i++) { 4 if(i%2==0){ 5 try { 6 sleep(1);//阻塞1mm 7 } catch (InterruptedException e) { 8 e.printStackTrace(); 9 } 10 System.out.println(Thread.currentThread().getName()+";"+i); 11 } 12 // if (i%2==0){ 13 // yield(); 14 // } 15 } 16 } 17 } 18 public class ThreadTest { 19 public static void main(String[] args) { 20 HelloThread he = new HelloThread(); 21 he.setName("线程1"); 22 he.start(); 23 24 Thread.currentThread().setName("主线程"); 25 26 for (int i = 0; i < 100; i++) { 27 if(i%2==0){ 28 29 System.out.println(Thread.currentThread().getName()+";"+i); 30 } 31 if (i==20){ 32 try { 33 he.join();//线程正常走,突然来了个join进来了,就走join的线程,走完join的再继续走原来的线程 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 } 37 } 38 } 39 40 } 41 42 }
3.1多线程示例之创建三个卖票窗口
class Window extends Thread{ private int ticket = 20; public void run(){ while (true){ if (ticket>0){ System.out.println(getName()+"卖票票号为"+ticket); ticket--; }else { break; } } } } public class WindowTest{ public static void main(String[] args) { Window w1 = new Window(); Window w2 = new Window(); Window w3 = new Window(); w1.setName("窗口1"); w2.setName("窗口2"); w3.setName("窗口3"); w1.start(); w2.start(); w3.start(); } }
4.线程的优先级设置
5.创建多线程方法二
5.1方法二示例
/** * 例子:创建三个窗口卖票,总票数为100张.使用实现Runnable接口的方式 * 存在线程的安全问题,待解决。 * * @author shkstart * @create 2019-02-13 下午 4:47 */ class Window1 implements Runnable{ private int ticket = 100; @Override public void run() { while(true){ if(ticket > 0){ System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket); ticket--; }else{ break; } } } } public class WindowTest1 { public static void main(String[] args) { Window1 w = new Window1(); Thread t1 = new Thread(w); Thread t2 = new Thread(w); Thread t3 = new Thread(w); t1.setName("窗口1"); t2.setName("窗口2"); t3.setName("窗口3"); t1.start(); t2.start(); t3.start(); } }
标签:Thread,start,线程,new,ticket,多线程,public 来源: https://www.cnblogs.com/jiangfc/p/16409175.html