16.Thead 多线程
发表日期:2021-06-30 19:58:59 | 来源: | | 浏览(924) 分类:JAVA基础
TheadDemo01
class MyThead extends Thread {
private int ticket =10;
private String name;
public MyThead(String name){
this.name = name;
}
public void run(){
for (int i = 0; i < 10; i++) {
if (this.ticket>0) {
System.out.println(name+":"+i+" ticket:"+ticket--);
}
}
}
}
public class TheadDemo01 extends Thread {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThead m1 = new MyThead("A");
MyThead m2 = new MyThead("B");
/*
m1.run();
m2.run();
A:0
A:1
A:2
A:3
A:4
A:5
A:6
A:7
A:8
A:9
B:0
B:1
B:2
B:3
B:4
B:5
B:6
B:7
B:8
B:9
run() 不会实现多线程
*/
m1.start();
m2.start();
}
}TheadDemo02
class MyThead2 implements Runnable{
private String name;
private int ticket =10;
public MyThead2(String name){
this.name = name;
}
public void run(){
for (int i = 0; i < 10; i++) {
if (ticket>0) {
System.out.println(name+":"+i+" ticket:"+ticket--);
}
}
}
public void start() {
// TODO Auto-generated method stub
}
}
public class TheadDemo02 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThead2 m1 = new MyThead2("A");
MyThead2 m2 = new MyThead2("B");
Thread t1 = new Thread(m1);
Thread t2 = new Thread(m2);
t1.start();
t2.start();
System.out.println(t2.getName());//setName() ...设置线程名称
}
}TheadDemo03
class MyThead3 implements Runnable{
private int ticket =10;
public MyThead3(){
}
public void run(){
for (int i = 0; i < 10; i++) {
if (this.ticket>0) {
System.out.println(i+" "+Thread.currentThread().getName()+" ticket:"+ticket--);
}
}
}
}
public class TheadDemo03 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThead3 mt = new MyThead3();
new Thread(mt,"A").start();
new Thread(mt,"B").start();
new Thread(mt,"C").start();
}
}
TheadDemo04
class MyThread4 implements Runnable{
private int ticket = 10;
public MyThread4(){
}
public void run(){
for (int i = 0; i < 10; i++) {
//System.out.println(name+":"+i);
if (this.ticket>0) {
System.out.println(Thread.currentThread().getName()+":"+i+" ticket:"+ticket--);
}
}
}
}
public class TheadDemo04 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyThread4 mt1 = new MyThread4();
new Thread(mt1).run();
new Thread(mt1).run();
}
}- JAVA(0)
- JAVA基础(30)
- 1.JAVA开发环境配置(0)
- 2.java数据类型(0)
- 3.数组(0)
- 4.Date(0)
- 5.String 和 StringBuffer类常用方法(0)
- 6.Math类(0)
- 7.Cloneable(0)
- 8.File 文件(0)
- 9.FileReader和FileWriter(0)
- 10.RandomAccessFile(0)
- 11.FileInputStream和FileOutputStream(0)
- 12.InputStreamReader和OutputStreamWriter(0)
- 13.BufferedReader(0)
- 14.Scanner(0)
- 15.DataOutputStream(0)
- 16.Thead 多线程(0)
- 17.TimerTask(0)
- 18.zip(0)
- 19.Charset(0)
- 20.List(0)
- 21.Map(0)
- 22.Properties(0)
- 23.Enumeration(0)
- 24.Collection(0)
- 25.JDBC(0)
- 26.Iterator(0)
- 27.Abstract(0)
- 28.Interface(0)
- 29.Serializable(0)
- 30.Camparable(0)
- JSP基础(50)
宁公网安备 64010402001209号