线程是比进程更小一级的执行单位,一个进程可以包含多个线程。多进程操作系统能同时运行多个进程(程序),由于 CPU 具备分时机制,所以每个进程都能循环获得自己的CPU 时间片。由于 CPU 执行速度非常快,使得所有程序好像是在同时运行一样。我们最常见的就是main方法可以看做一个进程或者是一个主线程,而在main方法里面开启的线程就是其子线程,他们同时存在,也可以同时运行。
public class myThread extends Thread{ private String name; public ThreadOne() {} public ThreadOne(String name) { super(); this.name = name; } public void run() { for(int i=0;i<10;i++) { System.out.println(name + i); } } }
//测试类
public class Test { public static void main(String[] args) { myThread t1 = new myThread("第一个线程:"); myThread t2 = new myThread("第二个线程:"); t1.start(); t2.start(); } }
public class myThread implements Runnable { private String name; public ThreadOne() { super(); } public ThreadOne(String name) { super(); this.name = name; } @Override public void run() { for(int i = 0; i < 10; i++) { System.out.println(name + i); } } }
//测试类
public class Test { public static void main(String[] args) { myThread threadOne = new myThread("第一个线程:"); myThread threadTwo = new myThread("第二个线程:"); Thread t1 = new Thread(threadOne); Thread t2 = new Thread(threadTwo); t1.start(); t2.start(); } }
public class myThread extends Thread{ public void run() { for(int i = 0; i < 10; i++) { System.out.println(getName + ":" + i); try{ Thread.sleep(100); } catch(InterruptException e){ e.printStackTrace(); } } } }
//测试类 public class Test { public static void main(String[] args) { myThread t1 = new myThread(); myThread t2 = new myThread(); t1.setName("cc") t2.setName("aa") t1.start(); t2.start(); } }
//测试类 public class Test { public static void main(String[] args) { Ticket tt = new Ticket(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); t1.setName("售票一"); t2.setName("售票二"); t1.start(); t2.start(); } }
//测试类 public class Test { public static void main(String[] args) { Ticket tt = new Ticket(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); t1.setName("售票一"); t2.setName("售票二"); t1.start(); t2.start(); } }
//测试类 public class Test { public static void main(String[] args) { Ticket tt = new Ticket(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); t1.setName("售票一"); t2.setName("售票二"); t1.start(); t2.start(); } }
//测试类 public class Test { public static void main(String[] args) { Ticket tt = new Ticket(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); t1.setName("售票一"); t2.setName("售票二"); t1.start(); t2.start(); } }