package com.demo.study.multithreading;
public class MyThread extends Thread{
private int i = 10;
// 可以自行定义锁,也可以使用实例的锁
Object mutex = new Object();
public void selltickets(){
synchronized (mutex) {
if(i>0){
i--;
//getName()获取线程的名字
System.out.println(Thread.currentThread().getName()+" :"+ i);
}
}
}
@Override
public void run() {
while(i>0){
selltickets();
}
}
}
package com.demo.study.multithreading;
public class Test {
public static void main(String[] args) {
//继承Thread方式:多线程多实例,无法实现资源的共享
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
//给线程命名
myThread1.setName("线程1");
myThread2.setName("线程2");
myThread1.start();
myThread2.start();
}
}
package com.demo.study.multithreading;
public class MyThreadImpl implements Runnable {
private int tickets = 10;
public void sellTickets() {
synchronized (MyThreadImpl.class) {
if (tickets > 0) {
tickets--;
System.out.println(Thread.currentThread().getName() + "正在卖票,还剩下" + tickets + "张");
}
}
}
@Override
public void run() {
while (tickets > 0) {
sellTickets();
try {
// 休眠一秒,让执行的效果更明显
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.demo.study.multithreading;
public class Test {
public static void main(String[] args) {
//只创建一个实例
MyThreadImpl threadImpl = new MyThreadImpl();
//将上面创建的唯一实例放入多个线程中,Thread类提供了多个构造方法,见下图(构造方法摘要)
Thread thread1 = new Thread(threadImpl, "窗口1");
Thread thread2 = new Thread(threadImpl, "窗口2");
thread1.start();
thread2.start();
}
}
| [b]构造方法摘要[/b] | |
|---|---|
| [code][b]Thread[/b]()[/code] 分配新的 [code]Thread[/code] 对象。 | |
| [code][b]Thread[/b](Runnable target)[/code] 分配新的 [code]Thread[/code] 对象。 | |
| [code][b]Thread[/b](Runnable target, String name)[/code] 分配新的 [code]Thread[/code] 对象。 | |
| [code][b]Thread[/b](String name)[/code] 分配新的 [code]Thread[/code] 对象。 | |
| [code][b]Thread[/b](ThreadGroup group, Runnable target)[/code] 分配新的 [code]Thread[/code] 对象。 | |
| [code][b]Thread[/b](ThreadGroup group, Runnable target, String name)[/code] 分配新的 [code]Thread[/code] 对象,以便将 [code]target[/code] 作为其运行对象,将指定的 [code]name[/code] 作为其名称,并作为 [code]group[/code] 所引用的线程组的一员。 | |
| [code][b]Thread[/b](ThreadGroup group, Runnable target, String name, long stackSize)[/code] 分配新的 [code]Thread[/code] 对象,以便将 [code]target[/code] 作为其运行对象,将指定的 [code]name[/code] 作为其名称,作为 [code]group[/code] 所引用的线程组的一员,并具有指定的[i]堆栈大小[/i]。 | |
| [code][b]Thread[/b](ThreadGroup group, String name)[/code] 分配新的 [code]Thread[/code] 对象。 | |
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有